我做了一项服务,可以检测其他应用程序是否启动。我已经为拨号器做了它。类似地,可以用任何包名称替换。
@Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
final String str = "";
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
int phonelaunched = 0,phoneclosed =0;
int phonelaunches = 1;
@Override
public void run() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
for ( ActivityManager.RunningAppProcessInfo appProcess: runningAppProcessInfo ) {
Log.d(appProcess.processName.toString(),"is running");
if (appProcess.processName.equals("com.android.dialer")) {
if ( appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND /*isForeground(getApplicationContext(),runningAppProcessInfo.get(i).processName)*/){
if (phonelaunched == 0 ){
phonelaunched = 1;
Log.d(str,"dude phone has been launched");
}
else if (phoneclosed == 1){
phonelaunches++;
phoneclosed = 0;
Log.d(String.valueOf(phonelaunches),"dude that was counter");
}
}
else {
phoneclosed = 1;
Log.d(str,"dude phone has been closed");
}
}
}
}
},2000,3000);
return START_STICKY;
}
在这里,我浏览了所有正在运行的任务并检查它是否是我们的预期应用程序。如果是这样,我检查应用程序是否在前台,并且应用程序从未使用“phonelaunched”变量启动。当预期的应用程序在后台并相应地设置变量时,使用 phoneclosed。
所有这些都在Service类中实现