• 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

    提示没有权限。

  • 相关阅读:
    前端 JavaScript&Dom
    前端 css续
    前端 初级篇(CSS)
    前端 初级篇(HTML)
    堡垒机
    Python操作RabbitMQ
    常用到代码片段
    关于文件上传功能的思考
    JS正则表达式将url转成json格式
    一行代码解决各种IE兼容问题,IE6,IE7,IE8,IE9,IE10
  • 原文地址:https://www.cnblogs.com/liyiran/p/4639095.html
Copyright © 2020-2023  润新知