-
创建一个AIDL
-
进行gradle构建成功之后会在此文件夹下出现此文件,可以在此aidl中自定义方法。
-
创建一个service
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;import com.henau.henau.examsystem.IMyAidlInterface;
public class AIDLService extends Service {
IMyAidlInterface.Stub stub=new IMyAidlInterface.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) throws RemoteException {
}@Override public String getName(String name) throws RemoteException { return name+"hahah"; }
};
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return stub;
}
}
此service中创建一个IMyAidlInterface对象并实现其中的方法,其中getName为自定义方法.
4.在Activity中进行绑定Service通过bindService方法
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.view.View;
import android.widget.Toast;
import com.henau.henau.examsystem.IMyAidlInterface;
import com.henau.henau.examsystem.R;
import com.henau.henau.examsystem.Service.AIDLService;
public class AIDL extends AppCompatActivity implements View.OnClickListener {
IMyAidlInterface iMyAidlInterface;
private ServiceConnection mServiceConnect=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aidl);
findViewById(R.id.start).setOnClickListener(this);
bindService(new Intent(AIDL.this, AIDLService.class),mServiceConnect,BIND_AUTO_CREATE);
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.start:
try {
String s = iMyAidlInterface.getName("xiaoliang");
Toast.makeText(AIDL.this,s,Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
}
通过iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);此方法得到IMyAidlInterface对象,通过此对象进行自动调用Service中的方法.