在Android5.0以前可以通過隱式Intent方式啟動其他App的Service,就跟Activity啟動隱式Intent一樣的。
但是在5.0以后,只能使用顯示的Intent方式啟動了。
啟動其他App的Service,需要用到Intent的setComponent()方法。該方法需要傳入ComponentName component 這個參數。
參數的解釋:component, The name of the application component to handle the intent, or null to let the system find one for you.
代碼:
1 Intent serviceIntent; 2 3 private Button btnstartService; 4 private Button btnstopService; 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_main); 10 11 serviceIntent=new Intent(); 12 serviceIntent.setComponent(new ComponentName("com.example.startservicefromanotherapp", "com.example.startservicefromanotherapp.AppService")); 13 14 btnstartService=(Button) findViewById(R.id.btnStartService); 15 btnstopService=(Button) findViewById(R.id.btnStopService); 16 17 btnstartService.setOnClickListener(this); 18 btnstopService.setOnClickListener(this); 19 } 20 21 @Override 22 public void onClick(View v) { 23 // TODO Auto-generated method stub 24 switch (v.getId()) { 25 case R.id.btnStartService: 26 startService(serviceIntent); 27 break; 28 29 case R.id.btnStopService: 30 stopService(serviceIntent); 31 break; 32 } 33 }
這樣就能啟動其他App的Service。但是需要先設置其他App的Service的
1 android:exported="true"
否則會報錯, java.lang.SecurityException: Not allowed to start service Intent { cmp=com.example.startservicefromanotherapp/.AppService } without permission not exported from uid 10075
提示沒有權限。