AIDL(Android Interface Definition Language)——安卓接口定义语言
一、startService/stopService
1、同一个应用程序启动Service:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this,AppService.class)); //启动Service
}
protected void onDestroy() {
super.onDestroy();
stopService(new Intent(this,AppService.class)); //停止Service
}
2、跨应用启动service:
通过Action的隐式Intent启动Service在安卓5.0以前的版本是可以实现跨应用启动Service的,安卓5.0以后的版本若想实现
跨应用启动Service的功能必须使用显示Intent。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Intent serviceIntent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serviceIntent = new Intent();
serviceIntent.setComponent(new ComponentName("com.w.startservicefromanotherapp","com.w.startservicefromanotherapp.AppService"));
findViewById(R.id.btnStartService).setOnClickListener(this);
findViewById(R.id.btnStopService).setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.btnStartService:
// Intent i = new Intent();
//i.setComponent(new ComponentName("com.w.startservicefromanotherapp","com.w.startservicefromanotherapp.AppService"));
//显示 Intent被启动程序的包名,被启动服务的类名
startService(serviceIntent);
break;
case R.id.btnStopService:
stopService(serviceIntent);
break;
}
}
}
二、bindService/unbindService
跨应用绑定Service:AIDL——用于在多个应用程序之间进行通信
1、在StartServiceFromAnotherApp新建AIDL文件IAppServiceRomoteBinder,会全自动生成相关的类。
2、在返回Binder时(AppService):
public IBinder onBind(Intent intent) {
return new IAppServiceRomoteBinder.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { }
};
}
3、在AnotherApp项目中绑定这个服务:
findViewById(R.id.btnBindService).setOnClickListener(this);
findViewById(R.id.btnUnbindService).setOnClickListener(this);
case R.id.btnBindService:
bindService(serviceIntent,this, Context.BIND_AUTO_CREATE);
break;
case R.id.btnUnbindService:
unbindService(this);
break;
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("Bind Service");
System.out.println(service); //显示IBinder service
}
@Override
public void onServiceDisconnected(ComponentName name) { }