Android在一个app中启动其他app中的service或者Activity

前言:

启动另一个app的activity和service其实是一样的,区别在于startActivity(intent)还是startService(intent)而已;所以下面案例以启动另一个app的服务为例;

第一种方式:

通过app包名全路径类名

Intent intent = new Intent(Intent.ACTION_VIEW);
String packageName = "com.ang.chapter_2_service"; //另一个app的包名
String className = "com.ang.chapter_2.poolBinder.BinderPoolService"; //另一个app要启动的组件的全路径名
intent.setClassName(packageName, className);
startService(intent);//或者bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 都能启动 

注意:另一个app中的Service别忘了在清单文件中注册 

如果设置了service的android:exported="true"属性,千万要为true ;如果为false,意味着不允许其他应用启动此service;

第二种方式:

通过ComponentName这个类启动

 ComponentName componetName = new ComponentName(
"com.ang.chapter_2_service",  //这个参数是另外一个app的包名
"com.ang.chapter_2.poolBinder.BinderPoolService");   //这个是要启动的Service的全路径名

Intent intent = new Intent();
intent.setComponent(componetName);
startService(intent); //或者bindService(intent, mConnection,Context.BIND_AUTO_CREATE);

注意:另一个app中的Service别忘了在清单文件中注册 ;如果设置了service的这android:exported="true"属性,千万要为true ;如果为false,意味着不允许其他应用启动此service;

第三种方式:

通过Activity或者Service的隐式启动的方式

1,此种方式这个要根据另一个app要启动的service设置了那些intent-filter;匹配规则很多,这里就不再具体阐述,最简单的方式如下:只设置了一个action,没有设置category和data

//另一个app中要启动的service的清单文件中注册信息 
<service android:name="com.ang.chapter_2.poolBinder.BinderPoolService"
         android:exported="true">
   <intent-filter>
       <action android:name="com.ang.poolBinder" />
   </intent-filter>
</service>

2,此app中的启动代码

Intent intent = new Intent();
intent.setPackage("com.ang.chapter_2_service");
intent.setAction("com.ang.poolBinder");
startService(intent)  //或者bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

注意事项和之前的一样

注意:另一个app 如果没有运行,不管是前台还是后台都没有,服务是启动不了的;不知为何,请大神指点一下,万分感谢!!

其他

启动其他app的办法,注意是app不是某个具体的activity或者service

Intent intent = context.getPackageManager().getLaunchIntentForPackage("另一个app的包名");
if (intent != null) {
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

猜你喜欢

转载自blog.csdn.net/ezconn/article/details/89068711