首页 > 学院 > 开发设计 > 正文

App之间通过Service相互唤醒保活

2019-11-09 14:05:23
字体:
来源:转载
供稿:网友

App之间通过Service相互唤醒保活

场景:有2个APP,分别为A和B,当A活着的时候,试着开启B的后台服务,将原本杀死的B的后台服务程序活起来。反之也一样。

示例代码(以A启动B为例):

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匹配规则。

效果图:

image


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表