如何检查从后台服务的Android应用程序在顶
在我的应用程序,我要检查whethere任何其他应用程序启动或无法从我的app.So我目前usimg Activitymanager找到像这样在顶
In my app i want to check whethere any other app launches or not from my app.So i am currently usimg Activitymanager to find the top activity like this
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
Log.d("topActivity", "CURRENT Activity ::"
+ taskInfo.get(0).topActivity.getClassName());
ComponentName componentInfo = taskInfo.get(0).topActivity;
componentInfo.getPackageName();
但我想运行此code在后台service.So,我可以检测到其他应用程序通过this.So启动有什么主意,做this.Plz帮助me.thanks
But i want to run this code in background service.So that i can detect When other app launches through this.So is there any idea to do this.Plz help me.thanks
通过使用服务,您可以做到这一点。
By using service you can achieve this..
public void checkActivity() {
handler = new Handler();
activityRunnable = new ActivityRunnable();
handler.postDelayed(activityRunnable, 500);
}
private class ActivityRunnable implements Runnable {
@Override
public void run() {
ActivityManager manager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
if (runningTasks != null && runningTasks.size() > 0) {
ComponentName topActivity = runningTasks.get(0).topActivity;
// Here you can get the TopActivity for every 500ms
if(!topActivity.getPackageName().equals(getPackageName())){
// Other Application is opened
}
handler.postDelayed(this, 500);
}
}
}
致电 checkActivity()
在服务
键,不要对的onCreate忘记删除 handler.removeCallbacks(activityRunnable);
在的onDestroy
Call the checkActivity()
in onCreate of service
and dont forgot to remove the handler.removeCallbacks(activityRunnable);
callbacks in onDestroy
开始LauncherActivity服务的onCreate
和停止LauncherActivity服务的onDestroy
start the service in LauncherActivity onCreate
and stop the service in LauncherActivity onDestroy
注意:不要忘了添加的权限在你的清单
Note: Dont forgot to add the permission in your manifest
<uses-permission android:name="android.permission.GET_TASKS" />