如何在android中使用其包名杀死任何应用程序

时间:2016-08-07 07:37:24

标签: android

我试图通过使用它的包名来杀死正在运行的应用程序:

String nameofProcess=your-package-name;
    ActivityManager manager=(ActivityManager)MainActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> listOfProcess=manager.getRunningAppProcesses();
    for(ActivityManager.RunningAppProcessInfo process:listOfProcess)
    {
        if(process.processName.contains(nameofProcess))
        {
            Log.e("Proccess" , process.processName + " : " + process.pid);
            android.os.Process.killProcess(process.pid);
            android.os.Process.sendSignal(process.pid, android.os.Process.SIGNAL_KILL);
            manager.killBackgroundProcesses(process.processName);
            break;
        }
    }

但它并没有杀死应用程序。当我去最近的任务时,它仍然存在。 有什么问题。

1 个答案:

答案 0 :(得分:3)

在清单文件中添加以下权限:

<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />

以下功能将使用其软件包名称终止应用程序:

private void killAppBypackage(String packageTokill){

        List<ApplicationInfo> packages;
        PackageManager pm;
        pm = getPackageManager();
        //get a list of installed apps.
        packages = pm.getInstalledApplications(0);


        ActivityManager mActivityManager = (ActivityManager) MainActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
        String myPackage = getApplicationContext().getPackageName();

        for (ApplicationInfo packageInfo : packages) {

            if((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM)==1) {
                continue;
            }
            if(packageInfo.packageName.equals(myPackage)) {
                continue;
            }
            if(packageInfo.packageName.equals(packageTokill)) {
                mActivityManager.killBackgroundProcesses(packageInfo.packageName);    
            }

        }

    }  

以下代码会杀死除当前应用和系统应用之外的所有正在运行的应用:

                List<ApplicationInfo> packages;
                PackageManager pm;
                pm = getPackageManager();
                //get a list of installed apps.
                packages = pm.getInstalledApplications(0);


                ActivityManager mActivityManager = (ActivityManager) MainActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
                String myPackage = getApplicationContext().getPackageName();

                for (ApplicationInfo packageInfo : packages) {

                    if((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM)==1) {
                        continue;
                    }
                    if(packageInfo.packageName.equals(myPackage)) {
                        continue;
                    }
                    mActivityManager.killBackgroundProcesses(packageInfo.packageName);
                }