用于检测其他应用程序是否正在运行的Android服务

时间:2015-05-20 12:47:37

标签: android android-intent

是否有像Intent.ACTION_SCREEN_OFF这样的操作来跟踪特定应用程序是否已启动?任何帮助将不胜感激!

if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Do something 
} else if (// application XYZ started) {
// Do something Else 
}

1 个答案:

答案 0 :(得分:0)

您可以查看应用程序是否正在运行:

ActivityManager activity_manager = (ActivityManager)context.getSystemService(Activity.ACTIVITY_SERVICE);
final   ActivityManager activityManager = (ActivityManager)       getSystemService(Context.ACTIVITY_SERVICE);
final List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks    (Integer.MAX_VALUE);
for (int i = 0; i < recentTasks.size(); i++) 
{
    Log.d("Executed app", "Application executed : " +recentTasks.get(i).baseActivity.toShortString()+ "\t\t ID: "+recentTasks.get(i).id+"");         
}

如果应用程序是前台:

public static boolean isForeground(Context ctx, String myPackage){
ActivityManager manager = (ActivityManager) ctx.getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > runningTaskInfo = manager.getRunningTasks(1); 

ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
if(componentInfo.getPackageName().equals(myPackage)) {
    return true;
}       
return false;
}