我试图创建一个Android应用程序,验证某个应用程序是否正在运行,如果某个应用程序未运行我的应用程序必须打开它,但我不知道如何做以验证某个应用程序是否是运行?请有人帮帮我...
答案 0 :(得分:0)
您可以使用TaskManager查看此示例代码 http://forum.xda-developers.com/attachment.php?attachmentid=2955965&stc=1&d=1412353638
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
/**recentTasks.get(0) Activity that is on top >> your app and number 1 will next **/
String pack = recentTasks.get(0).baseActivity.toShortString();
您也可以通过这样的UsageStats获取正在运行的应用程序的信息
try{
AppOpsManager appOps = (AppOpsManager) getSystemService(APP_OPS_SERVICE);
int mode = appOps.checkOp("android:get_usage_stats", android.os.Process.myUid(), getPackageName());
if(mode == AppOpsManager.MODE_ALLOWED) {//should turn on UsageStats
UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService(USAGE_STATS_SERVICE);
List<UsageStats> queryUsageStats = mUsageStatsManager
.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
System.currentTimeMillis() - 1000*60, //begin
System.currentTimeMillis()); //end
Collections.sort(queryUsageStats, new LastTimeLaunchedComparator());
try{
CustomUsageStats customUsageStats = new CustomUsageStats();
customUsageStats.usageStats = queryUsageStats.get(1);
String previousAppPack = customUsageStats.usageStats.getPackageName();
//the package of app before your app
}
catch (Exception e){}
}