public static void isOnTopOfActivty(Context context, String Packagename) {
String packname1 = null;
String packname2 = null;
ActivityManager mAm = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskList = mAm.getRunningTasks(2);
if (taskList.size() == 2) {
packname1 = taskList.get(0).topActivity.getPackageName();
packname2 = taskList.get(1).topActivity.getPackageName();
if (!packname1.equals(Packagename) && packname2.equals(Packagename)) {
if (packname1.contains("mms")) {
initializeKillMethod(context, packname1);
}
}
}
}
public static void initializeKillMethod(Context context, String packageName) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
Method killMethod = null;
try {
killMethod = ActivityManager.class.getMethod(
"killBackgroundProcesses", String.class);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
killMethod = ActivityManager.class.getMethod("restartPackage",
String.class);
killMethod.invoke(activityManager, packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
本方法只能让处于自己栈顶的方法被杀掉,但并不能保证自己一直处于栈顶。