Android Method for stopping other applications based on package name
- 2021-11-29 08:21:47
- OfStack
1. Use the killBackgroundProcesses () method
First add permissions to the AndroidManifest. xml file
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
Then call directly
stopApp(mContext,packageName)
Method
public void stopAppByKill(Context context ,String packageName) {
ActivityManager mActivityManager = (ActivityManager)
context.getSystemService(Context.ACTIVITY_SERVICE);
mActivityManager.killBackgroundProcesses(packageName);
2. forceStopPackage () method
This method belongs to the hidden method, needs to use the reflection mechanism to call, also needs to add the permission in the AndroidManifest. xml file and must first add in the application
android:sharedUserId="android.uid.system"
System-level permissions can call hidden methods
<uses-permission android:name="android.permission.FORCE_STOP_PACKAGES"/>
Then use reflection mechanism to call the method
public void stopAppByForce(Context context ,String packageName) {
ActivityManager mActivityManager = (ActivityManager)
context.getSystemService(Context.ACTIVITY_SERVICE);
Method method = null;
try {
method = Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", String.class);
method.invoke(mActivityManager, packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
Knowledge point supplement: Android obtains the names of other applications through package names
View the application name of this application:
getString(R.String.app_name);
View the application names of other applications:
public static String getApplicationNameByPackageName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
String Name ;
try {
Name=pm.getApplicationLabel(pm.getApplicationInfo(packageName,PackageManager.GET_META_DATA)).toString();
} catch (PackageManager.NameNotFoundException e) {
Name = "" ;
}
return Name
;}
Summarize