Android开发之AIDL的使用一--跨应用启动Service

时间:2023-03-08 15:52:28
Android开发之AIDL的使用一--跨应用启动Service

启动其他App的服务,跨进程启动服务。

与启动本应用的Service一样,使用startService(intent)方法

不同的是intent需要携带的内容不同,需要使用intent的setComponent()方法。

setComponent()方法需要传入两个参数,第一个参数是包名,第二个参数是组件名。即,第一个参数传入要启动的其他app的包名,第二个参数传入的时候要启动的其他app的service名。

看下面的例子:(aidlserviceapp应用通过button启动aidlservice应用MyService

aidlserviceapp应用:

 package com.example.aidlserviceapp;

 import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity implements OnClickListener { private Button btn_StartService, btn_StopService;
Intent serviceIntent = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serviceIntent = new Intent();
ComponentName componentName = new ComponentName(
"com.example.aidlservice", "com.example.aidlservice.MyService");
serviceIntent.setComponent(componentName); // 使用intent的setComponent()方法,启动其他应用的组件。 btn_StartService = (Button) findViewById(R.id.btn_StartService);
btn_StopService = (Button) findViewById(R.id.btn_StopService); btn_StartService.setOnClickListener(this);
btn_StopService.setOnClickListener(this); } @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_StartService:
startService(serviceIntent);
break;
case R.id.btn_StopService:
stopService(serviceIntent);
break;
default:
break;
}
}
}

aidlservice应用

 package com.example.aidlservice;

 import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log; public class MyService extends Service {
public static final String TAG = "aidlservice"; @Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "其他应用服务启动");
} @Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "其他应用服务停止");
} }

同时添加MyService在该应用的manifest。

1.启动aidlservice应用

2.启动aidlserviceapp应用

3.点击button,查看打印的log,是否启动了aidlservice应用的MyService服务。

结果如下图,启动成功。

Android开发之AIDL的使用一--跨应用启动Service