上一篇博客刚说到杀进程,会发现有的使用killBackgroundProcesses()方法是杀不死的。在这样的情况下就需要用到forceStopPackage()方法强制杀掉进程。各位小伙伴会发现使用mActivityManager.forceStopPackage()时该方法没有的情况。下面看看 源码:
/**
* 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());
}
这里有一个@hide的标签,因为谷歌觉得这样太不安全了,所以没法正常调用此方法,那么怎么办呢?我们第一时间就应该想到了用反射获取到此方法,然后进行调用。(注意此方法一定是系统级别签名的应用才能够调用此方法)
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();
}
如果不知道怎么获取应用包名的小伙伴,请看我上一篇博客:http://blog.csdn.net/qq77485042/article/details/76241102
下篇博客我将分享怎么把自己的应用push到system/app中,并且把自己的应用设置成系统级别的应用。
如有遗漏或错误,欢迎留言探讨。