Cómo matar el proceso en Android

El último blog acaba de hablar sobre matar procesos, y encontrará que algunos usan el método killBackgroundProcesses () para matarlos. En este caso, debe usar el método forceStopPackage () para detener el proceso a la fuerza. Todos encontrarán que este método no existe cuando se usa mActivityManager.forceStopPackage (). Echemos un vistazo al código fuente:

/**
     * Have the system perform a force stop of everything associated with
     * the given application package.  All processes that share its uid
     * will be killed, all services it has running stopped, all activities
     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
     * broadcast will be sent, so that any of its registered alarms can
     * be stopped, notifications removed, etc.
     *
     * <p>You must hold the permission
     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
     * call this method.
     *
     * @param packageName The name of the package to be stopped.
     * @param userId The user for which the running package is to be stopped.
     *
     * @hide This is not available to third party applications due to
     * it allowing them to break other applications by stopping their
     * services, removing their alarms, etc.
     */
    public void forceStopPackageAsUser(String packageName, int userId) {
        try {
            ActivityManagerNative.getDefault().forceStopPackage(packageName, userId);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

    /**
     * @see #forceStopPackageAsUser(String, int)
     * @hide
     */
    public void forceStopPackage(String packageName) {
        forceStopPackageAsUser(packageName, UserHandle.myUserId());
    }

Aquí hay una etiqueta @hide, porque Google cree que esto es demasiado inseguro, por lo que este método no se puede llamar normalmente, entonces, ¿qué debo hacer? Deberíamos haber pensado en usar la reflexión para obtener este método y luego llamarlo. (Tenga en cuenta que este método debe ser una aplicación firmada a nivel del sistema para poder llamar a este método)

ActivityManager mActivityManager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        Method method = null;
        try {
            method = Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", String.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            method.invoke(mActivityManager, packageName);  //packageName是需要强制停止的应用程序包名
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

Si no sabe cómo obtener el nombre del paquete de la aplicación, consulte mi último blog: http://blog.csdn.net/qq77485042/article/details/76241102

En el próximo blog, compartiré cómo enviar mi aplicación al sistema / aplicación y configurar mi aplicación como una aplicación a nivel de sistema.
Si hay omisiones o errores, deje un mensaje para discutir.

Supongo que te gusta

Origin blog.csdn.net/qq77485042/article/details/76329648
Recomendado
Clasificación