您的位置:首页 > 移动开发

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

2015-07-11 17:50 477 查看
在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

提示没有权限。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: