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

首頁 > 學院 > 開發設計 > 正文

App之間通過Service相互喚醒?;?/h1>
2019-11-09 15:00:03
字體:
來源:轉載
供稿:網友

場景:有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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

主站蜘蛛池模板: 富阳市| 青河县| 包头市| 屏南县| 洪江市| 米林县| 腾冲县| 确山县| 清水县| 建湖县| 灵寿县| 舟山市| 郎溪县| 惠东县| 万源市| 湘阴县| 南安市| 久治县| 济南市| 龙里县| 黄冈市| 家居| 日土县| 自治县| 通化县| 大渡口区| 遂昌县| 南康市| 大姚县| 西乌| 贵南县| 子长县| 海口市| 德兴市| 济宁市| 阿尔山市| 二连浩特市| 哈巴河县| 万安县| 明光市| 济阳县|