我想通过软件包名称关闭(杀死)我的应用程序中的另一个应用程序。我正在尝试类似的操作,但是此代码不会关闭任何应用程序。我在做什么错?
public void amKillProcess(string package_name)
{
ActivityManager am = (ActivityManager)this.GetSystemService(Context.ActivityService);
IList<RunningAppProcessInfo> runningProcesses = am.RunningAppProcesses;
foreach (RunningAppProcessInfo runningProcess in runningProcesses)
{
if (runningProcess.ProcessName.Contains(package_name))
{
Android.OS.Process.SendSignal(runningProcess.Pid, Signal.Kill);
am.KillBackgroundProcesses(runningProcess.ProcessName);
}
}
}
P.S,我添加了android.permission.KILL_BACKGROUND_PROCESSES
,通过此代码,我只能关闭自己的应用程序
如果您想终止后台应用程序,请检查以下代码
public void amKillProcess(string package_name)
{
ActivityManager am = (ActivityManager)this.GetSystemService(Context.ActivityService);
var runningProcesses = am.RunningAppProcesses;
foreach (RunningAppProcessInfo runningProcess in runningProcesses)
{
if (runningProcess.ProcessName.Contains(package_name))
{
Android.OS.Process.KillProcess(runningProcess.Uid);
}
}
}
并且,如果您想终止前台应用程序,则可以使用Adb
public class SuUtil
{
private static Java.Lang.Process process;
public static void kill(string packageName)
{
initProcess();
killProcess(packageName);
close();
}
private static void initProcess()
{
if (process == null)
try
{
process = Runtime.GetRuntime().Exec("su");
}
catch (IOException e)
{
}
}
private static void killProcess(string packageName)
{
System.IO.Stream output = process.OutputStream;
Java.Lang.String cmd = new Java.Lang.String("am force-stop " + packageName + " \n");
try
{
output.Write(cmd.GetBytes());
output.Flush();
}
catch (IOException e)
{
}
}
private static void close()
{
if (process != null)
try
{
process.OutputStream.Close();
process = null;
}
catch (IOException e)
{
}
}
}