您好,登錄后才能下訂單哦!
這篇文章主要介紹了Android如何檢測Activity或者Service是否運行,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
需求:假設我們的APP有3個頁面AActivity,BActivity,CActivity,我們的APP需要一直運行在前臺(特殊設備),要求實現一個監控服務,來監視APP是否運行,如果有3個頁面都不運行了就說明這個APP已經掛掉了,否則說明APP在運行狀態,不做處理,掛掉之后,我們需要重新啟動App來讓它繼續處理運行狀態,對外暴露一個來停止監控服務的廣播,這樣我們想停止監控服務時,發送一個廣播即可。
思路:實現一個雙進程的監控服務,服務中寫一個定時器 Timer 來重復進行檢測是否正在運行,如果否就直接重新啟動APP。
1.定義一個監控服務
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:殺死自己的進程!"); killMyselfPid(); // 殺死自己的進程 } } }; private Timer timer = new Timer(); private TimerTask task = new TimerTask() { @Override public void run() { checkIsAlive(); } }; /** * 檢測應用是否活著 */ 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: 啟動監控服務! "); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("kill_self"); registerReceiver(broadcastReceiver, intentFilter); timer.schedule(task, 0, 10000);// 設置檢測的時間周期(毫秒數) } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public IBinder onBind(Intent arg0) { return null; } /** * 殺死自身的進程 */ 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.注冊雙進程Service
<service android:name="com.xpf.monitor.MonitoringService" android:enabled="true" android:label="MonitoringService" android:process=":gray"> <intent-filter> <action android:name="android.intent.action.RESPOND_VIA_MESSAGE" /> </intent-filter> </service>
3.檢測是否活著的工具類CheckUtil
public class CheckUtil { //檢測service是否在運行 public static boolean isServiceWorked(Context context, String serviceName) { ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) 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<ActivityManager.RunningTaskInfo> task = myManager.getRunningTasks(1); ComponentName componentInfo = task.get(0).topActivity; if (componentInfo.getPackageName().equals(PackageName)) return true; return false; } /** * 判斷某個app進程是否在運行 * * @param context * @param appInfo * @return */ public static boolean isRunningProcess(Context context, String appInfo) { ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> runningAppPs = myManager.getRunningAppProcesses(); if (runningAppPs != null && runningAppPs.size() > 0) { if (runningAppPs.contains(appInfo)) { return true; } } return false; } /** * 判斷一個Activity是否正在運行 * * @param pkg pkg為應用包名 * @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<ActivityManager.RunningTaskInfo> 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中啟動監控服務
Intent intent = new Intent(MainActivity.this, MonitoringService.class); intent.setAction("android.intent.action.RESPOND_VIA_MESSAGE"); startService(intent);
5.停止監控服務
發送一個殺死進程廣播即可,action值如下
Intent intent = new Intent(); intent.setAction("kill_self"); sendOrderedBroadcast(intent, null);
感謝你能夠認真閱讀完這篇文章,希望小編分享的“Android如何檢測Activity或者Service是否運行”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。