有时候我们需要监听app的启动,并在一定时间进行拦截,其实系统是有提供相应的监听方法的
我们需要申明以下权限
<uses-permission android:name=".SET_ACTIVITY_WATCHER" />
其次我们需要进行注册
import ;
import ;
import ;
setActivityController();
private void setActivityController() {
IActivityManager am = ();
try {
("ActivityController", "setActivityController");
(new ActivityController(this),true);
} catch (RemoteException e) {
("ActivityController", "setActivityController RemoteException");
();
}
}
然后我们就去实现对应回调方法
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class ActivityController extends {
public ActivityController(Context context){
}
/**activityStarting:当系统正在启动一个activity时会触发,当返回true,表示允许启动。当返回状态noraml/false分别表示停止/拒绝启动activity
activityResuming:当系统正在返回一个activity时会触发,当返回true,表示允许返回。当返回状态noraml/false分别表示停止/拒绝返回activity
appCrashed:当一个应用进程已经崩溃会触发,当返回true时,表示可以重启,当返回false时,表示立即杀死它(进程)。
appEarlyNotResponding:当一鉴定为ANR时就很早触发;
appNotResponding:当一个应用进程出现ANR时就会触发,当返回0时,表示会弹出应用无响应的dialog,如果返回1时,表示继续等待,如果返回-1时,表示立即杀死进程。
systemNotResponding:当系统看门狗已经监测到系统似乎挂起就会触发,如果放回1时,表示继续等待,如果返回-1时,就让系统进行正常的自杀(这里的正常自杀,我的理解是系统自己主动自杀,该保存的数据先保存等然后就自杀,并不是因为其他原因导致的自杀)**/
public boolean activityStarting(Intent intent, String pkg) throws RemoteException {
return true;
}
public boolean activityResuming(String pkg) throws RemoteException {
return true;
}
public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg, long timeMillis, String stackTrace) throws RemoteException {
return true;
}
public int appEarlyNotResponding(String processName, int pid, String annotation) throws RemoteException {
return 0;
}
public int appNotResponding(String processName, int pid, String processStats) throws RemoteException {
return 0;
}
public int systemNotResponding(String msg) throws RemoteException {
return 0;
}
}
以上方法只能系统级应用才能监听