Android通过反射实现强制停止应用程序的方法

时间:2022-03-01 08:13:19

本文实例讲述了Android通过反射实现强制停止应用程序的方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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

?
1
2
3
4
<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程序设计有所帮助。