啟動其他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服務。
結果如下圖,啟動成功。