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

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

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

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

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

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

aidlserviceapp应用:

 1 package com.example.aidlserviceapp;
 2 
 3 import android.app.Activity;
 4 import android.content.ComponentName;
 5 import android.content.Intent;
 6 import android.os.Bundle;
 7 import android.view.View;
 8 import android.view.View.OnClickListener;
 9 import android.widget.Button;
10 
11 public class MainActivity extends Activity implements OnClickListener {
12 
13     private Button btn_StartService, btn_StopService;
14     Intent serviceIntent = null;
15 
16     @Override
17     protected void onCreate(Bundle savedInstanceState) {
18         super.onCreate(savedInstanceState);
19         setContentView(R.layout.activity_main);
20         serviceIntent = new Intent();
21         ComponentName componentName = new ComponentName(
22                 "com.example.aidlservice", "com.example.aidlservice.MyService");
23         serviceIntent.setComponent(componentName); // 使用intent的setComponent()方法,启动其他应用的组件。
24 
25         btn_StartService = (Button) findViewById(R.id.btn_StartService);
26         btn_StopService = (Button) findViewById(R.id.btn_StopService);
27 
28         btn_StartService.setOnClickListener(this);
29         btn_StopService.setOnClickListener(this);
30 
31     }
32 
33     @Override
34     public void onClick(View v) {
35         switch (v.getId()) {
36         case R.id.btn_StartService:
37             startService(serviceIntent);
38             break;
39         case R.id.btn_StopService:
40             stopService(serviceIntent);
41             break;
42         default:
43             break;
44         }
45     }
46 }

aidlservice应用

 1 package com.example.aidlservice;
 2 
 3 import android.app.Service;
 4 import android.content.Intent;
 5 import android.os.IBinder;
 6 import android.util.Log;
 7 
 8 public class MyService extends Service {
 9     public static final String TAG = "aidlservice";
10 
11     @Override
12     public IBinder onBind(Intent intent) {
13         return null;
14     }
15 
16     @Override
17     public void onCreate() {
18         super.onCreate();
19         Log.e(TAG, "其他应用服务启动");
20     }
21 
22     @Override
23     public void onDestroy() {
24         super.onDestroy();
25         Log.e(TAG, "其他应用服务停止");
26     }
27 
28 }

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

1.启动aidlservice应用

2.启动aidlserviceapp应用

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

结果如下图,启动成功。

 

原文地址:https://www.cnblogs.com/liyiran/p/4930051.html