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

在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

提示没有权限。

转载于:https://www.cnblogs.com/liyiran/p/4639095.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值