Recently, I want to create a task manager on the Android 2.2 platform. The former API: restartpackage is invalid on Android 2.2.
The restartpackage API is valid on platforms 1.5 and 1.6: activitymanager. restartpackage (pakagename );
The test failed multiple times on 2.2. Later, I checked the framework and found that it was blocked by Google? No alternative API is found.
If you have system permissions,
1. Use the following code
@SuppressWarnings({ "rawtypes" }) private boolean killProcessByPkg(String pkgName){ Class c; try { c = Class.forName("android.app.ActivityManagerNative"); Method getDefaultMethod = c.getMethod("getDefault"); getDefaultMethod.setAccessible(true); Object nativeManager = getDefaultMethod.invoke(null); c = nativeManager.getClass(); Method forceStopPackageMethod = c.getMethod("forceStopPackage", String.class); forceStopPackageMethod.setAccessible(true); forceStopPackageMethod.invoke(nativeManager, pkgName); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return true; }
2. Add permission to the manifist file:
android.permission.FORCE_STOP_PACKAGES
3. Create an android. mk file.
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) #LOCAL_MODULE_TAGS := optional LOCAL_SRC_FILES := $(call all-java-files-under, src) LOCAL_PACKAGE_NAME := TestKillProcess LOCAL_CERTIFICATE := platform include $(BUILD_PACKAGE) # Use the folloing include to make our test apk. include $(call all-makefiles-under,$(LOCAL_PATH))
4. Compile and use the APK File
ADB install <your APK File>
If the installation is successful, you have system permissions and can use it.
I tried emulator successfully.
If you do not have system permissions,
Private activitymanager am;
AM = (activitymanager) This. getsystemservice (service. activity_service );
Am. killbackgroundprocesses (packagename );
Yes, but make sure that the process you want to kill is in the onstop state.