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ī)則。
效果圖:

|
新聞熱點
疑難解答