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匹配規則。
效果圖:
新聞熱點
疑難解答