本文实例讲述了Android通过反射实现强制停止应用程序的方法。分享给大家供大家参考,具体如下:
private ActivityManager manager; private List<RunningAppProcessInfo> runningProcesses; private String packName; private PackageManager pManager; @Override public void onReceive(Context context, Intent intent) { pManager = context.getPackageManager(); manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); killOthers(context); } /** * 杀死其他正在运行的程序 * * @param context */ private void killOthers(Context context) { runningProcesses = manager.getRunningAppProcesses(); for (RunningAppProcessInfo runningProcess : runningProcesses) { try { packName = runningProcess.processName; ApplicationInfo applicationInfo = pManager.getPackageInfo(packName, 0).applicationInfo; if (!"com.asms".equals(packName)&&filterApp(applicationInfo)) { forceStopPackage(packName,context); System.out.println(packName+"JJJJJJ"); } }catch(Exception e){ e.printStackTrace(); } } } /** *强制停止应用程序 * @param pkgName */ private void forceStopPackage(String pkgName,Context context) throws Exception{ ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); Method method = Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", String.class); method.invoke(am, pkgName); } /** * 判断某个应用程序是 不是三方的应用程序 * @param info * @return */ public boolean filterApp(ApplicationInfo info) { if ((info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) { return true; } else if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { return true; } return false; }
说明:如果是在Activity中将onReceiver方法换成onCreate方法即可。
2.需要在AndroidManifest.xml 把package的userid设置为system
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.asms" android:versionCode="1" android:versionName="1.0" android:sharedUserId="android.uid.system">
希望本文所述对大家Android程序设计有所帮助。