1.先看B的代码:
创建一个服务YibaServcie,给服务添加一个process属性,设置action。
<service
android:name=".YibaService"
android:process=":test">
<intent-filter>
<action android:name="com.yiba" />
intent-filter>
service>
YibaService的代码,在onStartCommand方法中弹出toast:
public class YibaService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "YibaService 已经唤醒", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
}
2.看A的代码,在MainActivity中点击开启B应用的YibaService服务的代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendService();
}
});
}
private void sendService() {
boolean find = false;
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
Intent serviceIntent = new Intent();
for (ActivityManager.RunningServiceInfo runningServiceInfo : mActivityManager.getRunningServices(100)) {
if (runningServiceInfo.process.contains(":test")) {//判断service是否在运行
Log.e("zhang", "process:" + runningServiceInfo.process);
find = true;
}
}
//判断服务是否起来,如果服务没起来,就唤醒
if (!find) {
serviceIntent.setPackage("com.yiba.test.yibaapp");
serviceIntent.setAction("com.yiba");
startService(serviceIntent);
Toast.makeText(this, "开始唤醒 YibaServcie", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "YibaServcie 不用唤醒", Toast.LENGTH_SHORT).show();
}
}
}
这里只是写了A启动B服务的代码,反之也是一样的。被启动应用的Servcie在AndroidMainfest.xml中注册时注意,添加process属性,和设置action匹配规则。
效果图: