从Android document 中了解一下用API 杀死当前应用进程的问题

1.android.os.Process  这个类里面的方法:

public static final void killProcess (int pid)
Kill the process with the given PID. Note that, though this API allows us to request to kill any process based on its PID, the kernel will still impose standard restrictions on which PIDs you are actually able to kill. Typically this means only the process running the caller's packages/application and any additional processes created by that app; packages sharing a common UID will also be able to kill each other's processes.

PID (Process Identifier):进程标志符  UID(User Identifier):用户标志符


这句话简单理解为:此方法可以根据提供的进程标志符来来杀死进程,但是Linux 会根据标准的限制条件来决定是否能够杀死此进程:能够杀死这个应用程序的主进程,能够杀死由主进程产生的进程,能够杀死共享同一个用户标志符的进程。


代码实例如下:

android.os.Process.killProcess(android.os.Process.myPid());


次方法不需要任何权限。


2. android.app.ActivityManager  这个类里面的方法

public void killBackgroundProcesses(String packageName)

Have the system immediately kill all background processes associated with the given package. This is the same as the kernel killing those processes to reclaim memory; the system will take care of restarting these processes in the future as needed.

You must hold the permission KILL_BACKGROUND_PROCESSES to be able to call this method.


实例代码如下所示 :

ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);    

manager.killBackgroundProcesses(getPackageName());



在Manifest 中声明的权限如下:

 <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>




接着看方法3。


3.同样 android.app.ActivityManager  这个类

public void restartPackage(String packageName)

This method was deprecated in API level 8.
This is now just a wrapper for killBackgroundProcesses(String); the previous behavior here is no longer available to applications because it allows them to break other applications by removing their alarms, stopping their services, etc.


实例代码如下所示:

ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);       
manager.restartPackage(getPackageName());

在Manifest 中声明的权限如下:

 <uses-permission android:name="android.permission.RESTART_PACKAGES"/>

方法3 restartPackage 是方法2 killBackgroundProcesses 封装方法 ,但是在 API level 8 已经废弃,之后的版本不再使用。


4. 调用 System.exit(0)。

Causes the VM to stop running and the program to exit with the given exit status.

停止VM ,Android 一个VM 对应一个应用程序,停止VM 也就是停止当前应用程序。

当调用System.exit(0)时,杀死了整个进程,这时候活动所占的资源也会被释放。





推荐使用方法1和方法4.

















  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值