国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設(shè)計 > 正文

App之間通過Service相互喚醒保活

2019-11-09 14:05:23
字體:
供稿:網(wǎng)友

App之間通過Service相互喚醒保活

場景:有2個APP,分別為A和B,當A活著的時候,試著開啟B的后臺服務(wù),將原本殺死的B的后臺服務(wù)程序活起來。反之也一樣。

示例代碼(以A啟動B為例):

1.先看B的代碼:

創(chuàng)建一個服務(wù)YibaServcie,給服務(wù)添加一個PRocess屬性,設(shè)置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 已經(jīng)喚醒", Toast.LENGTH_SHORT).show(); return START_STICKY; }}

2.看A的代碼,在MainActivity中點擊開啟B應(yīng)用的YibaService服務(wù)的代碼:

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; } } //判斷服務(wù)是否起來,如果服務(wù)沒起來,就喚醒 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服務(wù)的代碼,反之也是一樣的。被啟動應(yīng)用的Servcie在AndroidMainfest.xml中注冊時注意,添加process屬性,和設(shè)置action匹配規(guī)則。

效果圖:

image


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 福安市| 宜昌市| 聂荣县| 资兴市| 容城县| 舟曲县| 工布江达县| 陕西省| 敦煌市| 襄城县| 汽车| 措美县| 阳高县| 霍州市| 锦州市| 阜平县| 莎车县| 遵义市| 牡丹江市| 乐都县| 商河县| 城固县| 三江| 陆丰市| 河源市| 凤庆县| 大石桥市| 石楼县| 塘沽区| 怀来县| 通州区| 东阳市| 长春市| 建昌县| 腾冲县| 连城县| 伊川县| 遵义市| 遵义市| 青海省| 澄城县|