這篇文章主要介紹了Android如何檢測Activity或者Service是否運行,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
成都創(chuàng)新互聯(lián)自2013年創(chuàng)立以來,先為會澤等服務(wù)建站,會澤等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為會澤企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
需求:假設(shè)我們的APP有3個頁面AActivity,BActivity,CActivity,我們的APP需要一直運行在前臺(特殊設(shè)備),要求實現(xiàn)一個監(jiān)控服務(wù),來監(jiān)視APP是否運行,如果有3個頁面都不運行了就說明這個APP已經(jīng)掛掉了,否則說明APP在運行狀態(tài),不做處理,掛掉之后,我們需要重新啟動App來讓它繼續(xù)處理運行狀態(tài),對外暴露一個來停止監(jiān)控服務(wù)的廣播,這樣我們想停止監(jiān)控服務(wù)時,發(fā)送一個廣播即可。
思路:實現(xiàn)一個雙進(jìn)程的監(jiān)控服務(wù),服務(wù)中寫一個定時器 Timer 來重復(fù)進(jìn)行檢測是否正在運行,如果否就直接重新啟動APP。
1.定義一個監(jiān)控服務(wù)
package com.anloq.nfcservice; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; import android.util.Log; import com.anloq.MyApplication; import com.anloq.activity.AdActivity; import com.anloq.utils.DetectionASUtils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; /** * Created by xpf on 2017/6/3 :) * 檢測APP頁面是否一直運行,不運行就直接啟動 */ public class MonitoringService extends Service { private final static String TAG = "MonitoringService"; private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if ("kill_self".equals(intent.getAction())) { Log.e(TAG, "onReceive:殺死自己的進(jìn)程!"); killMyselfPid(); // 殺死自己的進(jìn)程 } } }; private Timer timer = new Timer(); private TimerTask task = new TimerTask() { @Override public void run() { checkIsAlive(); } }; /** * 檢測應(yīng)用是否活著 */ private void checkIsAlive() { String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date()); Log.e(TAG, "CustodyService Run: " + format); boolean AIsRunning = CheckUtil.isClsRunning( MonitoringService.this, "com.xpf.monitor", "com.xpf.monitor.activity.AActivity"); boolean BIsRunning = CheckUtil.isClsRunning( MonitoringService.this, "com.xpf.monitor", "com.xpf.monitor.activity.BActivity"); boolean b = (AIsRunning || BIsRunning); boolean CIsRunning = CheckUtil.isClsRunning( MonitoringService.this, "com.xpf.monitor", "com.xpf.monitor.activity.CActivity"); Log.e(TAG, "AIsRunning || BIsRunning is running:" + b + ",CIsRunning:" + CIsRunning); if (!CIsRunning) { if (!b) { //如果界面掛掉直接啟動AActivity Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setClass(MonitoringService.this, AActivity.class); startActivity(intent); } } } @Override public void onCreate() { super.onCreate(); Log.e(TAG, "onCreate: 啟動監(jiān)控服務(wù)! "); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("kill_self"); registerReceiver(broadcastReceiver, intentFilter); timer.schedule(task, 0, 10000);// 設(shè)置檢測的時間周期(毫秒數(shù)) } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public IBinder onBind(Intent arg0) { return null; } /** * 殺死自身的進(jìn)程 */ private void killMyselfPid() { int pid = android.os.Process.myPid(); String command = "kill -9 " + pid; Log.e(TAG, "killMyselfPid: " + command); stopService(new Intent(MonitoringService.this, MonitoringService.class)); try { Runtime.getRuntime().exec(command); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(broadcastReceiver); if (task != null) { task.cancel(); } if (timer != null) { timer.cancel(); } } }
2.注冊雙進(jìn)程Service
3.檢測是否活著的工具類CheckUtil
public class CheckUtil { //檢測service是否在運行 public static boolean isServiceWorked(Context context, String serviceName) { ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); ArrayListrunningService = (ArrayList ) myManager.getRunningServices(Integer.MAX_VALUE); for (int i = 0; i < runningService.size(); i++) { if (runningService.get(i).service.getClassName().toString().equals(serviceName)) { return true; } } return false; } //檢測activity是否存在再棧頂 public static boolean isForeground(Context context, String PackageName) { ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List task = myManager.getRunningTasks(1); ComponentName componentInfo = task.get(0).topActivity; if (componentInfo.getPackageName().equals(PackageName)) return true; return false; } /** * 判斷某個app進(jìn)程是否在運行 * * @param context * @param appInfo * @return */ public static boolean isRunningProcess(Context context, String appInfo) { ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List runningAppPs = myManager.getRunningAppProcesses(); if (runningAppPs != null && runningAppPs.size() > 0) { if (runningAppPs.contains(appInfo)) { return true; } } return false; } /** * 判斷一個Activity是否正在運行 * * @param pkg pkg為應(yīng)用包名 * @param cls cls為類名eg * @param context * @return */ public static boolean isClsRunning(Context context, String pkg, String cls) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List tasks = am.getRunningTasks(1); ActivityManager.RunningTaskInfo task = tasks.get(0); if (task != null) { return TextUtils.equals(task.topActivity.getPackageName(), pkg) && TextUtils.equals(task.topActivity.getClassName(), cls); } return false; } }
4.MainActivity中啟動監(jiān)控服務(wù)
Intent intent = new Intent(MainActivity.this, MonitoringService.class); intent.setAction("android.intent.action.RESPOND_VIA_MESSAGE"); startService(intent);
5.停止監(jiān)控服務(wù)
發(fā)送一個殺死進(jìn)程廣播即可,action值如下
Intent intent = new Intent(); intent.setAction("kill_self"); sendOrderedBroadcast(intent, null);
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Android如何檢測Activity或者Service是否運行”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!