Android开发之通过Intent启动其他App的Service

时间:2023-06-05 12:09:50

在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.

代码:

     Intent serviceIntent;

     private Button btnstartService;
private Button btnstopService; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); serviceIntent=new Intent();
serviceIntent.setComponent(new ComponentName("com.example.startservicefromanotherapp", "com.example.startservicefromanotherapp.AppService")); btnstartService=(Button) findViewById(R.id.btnStartService);
btnstopService=(Button) findViewById(R.id.btnStopService); btnstartService.setOnClickListener(this);
btnstopService.setOnClickListener(this);
} @Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnStartService:
startService(serviceIntent);
break; case R.id.btnStopService:
stopService(serviceIntent);
break;
}
}

这样就能启动其他App的Service。但是需要先设置其他App的Service的

 android:exported="true"

否则会报错, java.lang.SecurityException: Not allowed to start service Intent { cmp=com.example.startservicefromanotherapp/.AppService } without permission not exported from uid 10075

提示没有权限。