一,先写服务端
1,先在main下新建一个aidl的package,然后新建一个aidl的接口文件。
// ICalculatorService.aidl
package com.example.may;
// Declare any non-default types here with import statements
interface ICalculatorService {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
float calculate(float x,float y,char option);
}
然后build下项目,会生成一些aidl的文件
2,实现具体服务
package com.example.may.aidl学习;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.example.may.ICalculatorService;
import androidx.annotation.Nullable;
public class CalculatorService extends Service {
private ICalculatorService.Stub mBinder=new ICalculatorService.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) {
}
@Override
public float calculate(float x, float y, char option) {
Log.d("binder","service myPid="+android.os.Process.myPid());
Log.d("binder","service thread="+Thread.currentThread().getName());
Log.d("binder","x="+x+"y="+y);
switch (option){
case '+':
return x+y;
case '-':
return x-y;
case '/':
if(y!=0){
return x/y;
}else{
Log.d("binder","被除数为0,不合法");
return 0;
}
case '*':
return x*y;
default:
return 0;
}
}
};
//构造方法在onCreate之前
public CalculatorService(){
Log.d("binder","constructor");
}
@Override
public void onCreate() {
super.onCreate();
Log.d("binder","onCreate");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
//通过intent,客户端可以给server传递消息
String info= intent.getStringExtra("extra");
Log.d("binder","info="+info);
Log.d("binder","onBind"+" action="+intent.getAction()+" package="+intent.getPackage());
int check=checkCallingOrSelfPermission("com.example.may.permission.LOCAL");
if(check== PackageManager.PERMISSION_DENIED){
Log.d("binder","client does not get permission");
return null;
}
return mBinder;//将binder的引用提供出去
}
}
3,在配置文件里开启权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.may">
<uses-permission android:name="com.example.may.permission.LOCAL"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Author.AuthorListActivity"
android:theme="@style/MyCustomTheme"
>
</activity>
<activity android:name=".User.UserListActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".aidl学习.CalculatorService"
>
<intent-filter
>
<action android:name="com.example.may.aidl学习.CalculatorService"></action>
</intent-filter>
</service>
</application>
</manifest>
二,实现客户端
1,将服务端里的aidl的package,copy到main目录下。
然后build下项目。
// ICalculatorService.aidl
package com.example.may;
// Declare any non-default types here with import statements
interface ICalculatorService {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
float calculate(float x,float y,char option);
}
2,在配置文件种要将权限打开
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.student">
<permission android:name="com.example.may.permission.LOCAL"></permission>
<uses-permission android:name="com.example.may.permission.LOCAL"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3,获取到服务端的binder,并实现通信
package com.example.student;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.example.may.ICalculatorService;
public class MainActivity extends AppCompatActivity {
private ICalculatorService mICalculatorService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button)findViewById(R.id.btn_startCalcul);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float res = 0;
try {
res = mICalculatorService.calculate(7,8,'+');
} catch (RemoteException e) {
e.printStackTrace();
}
Log.d("binder","the res="+res);
}
});
}
@Override
protected void onStart() {
super.onStart();
Log.d("binder","onStart");
Intent intent=new Intent();
intent.setAction("com.example.may.aidl学习.CalculatorService");
//服务的action是这样的
intent.setPackage("com.example.may");//说明要访问的服务在哪个进程
intent.putExtra("extra","i am from com.example.student");
intent.putExtra("我来自com.example.student",100);
bindService(intent,connection,BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
unbindService(connection);
}
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("binder","onServiceConnected");
//mICalculatorService=(ICalculatorService)service;
//注意,这里不能用这种方式获取service,这是一个大坑,在这里浪费了好多时间
mICalculatorService= ICalculatorService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d("binder","onServiceConnected");
}
};
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_startCalcul"
android:text="开始计算"
android:layout_marginTop="100dp"
></Button>
</LinearLayout>