zoukankan      html  css  js  c++  java
  • 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

    提示没有权限。

  • 相关阅读:
    学习 TList 类的实现[1]
    Dll 使用 PChar 参数的小例子
    学习使用资源文件[11]
    【转载】OGRE 内存管理
    【转载】Ogre的内存分配策略
    【转载】.NET面试题系列[0]
    【转载】深入探讨透视投影坐标变换
    【转载】四元数-Quaterion
    【转载】齐次坐标
    【转载】深入研究Windows内部原理绝对经典的资料
  • 原文地址:https://www.cnblogs.com/liyiran/p/4639095.html
Copyright © 2011-2022 走看看