android关闭应用
2011-03-12 16:28
204 查看
在开发一个android应用软件时,考虑如何关闭应用程序的问题。一开始采用当前Activity调用finish()来完成,但这种做法是不对的。 这几天通过阅读Android的frameworks层代码时,发现平台提供了关闭程序的方法。 在ActivityManager类中提供了如下的方法:
如下:
/**
* 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.
*
* You must hold the permission * {@link android.Manifest.permission#RESTART_PACKAGES} to be able to
* call this method.
*
* @param packageName The name of the package to be stopped.
*/
public void restartPackage(String packageName) {
try {
ActivityManagerNative.getDefault().restartPackage(packageName);
} catch (RemoteException e) { } }
ok,我们只需要取得ActivityManager的实例,并调用该方法即可正常关闭应用。 以下是关闭程序的代码片段:
private void exit2() {
ActivityManager actMgr = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
actMgr.restartPackage(getPackageName()); }
调用上述方法就能彻底地关闭掉程序,一般仅仅调用finish()是无法彻底关闭程序的。 但要注意一点,调用系统服务需要在AndroidManifest.xml文件中增加权限。
如下:
/**
* 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.
*
* You must hold the permission * {@link android.Manifest.permission#RESTART_PACKAGES} to be able to
* call this method.
*
* @param packageName The name of the package to be stopped.
*/
public void restartPackage(String packageName) {
try {
ActivityManagerNative.getDefault().restartPackage(packageName);
} catch (RemoteException e) { } }
ok,我们只需要取得ActivityManager的实例,并调用该方法即可正常关闭应用。 以下是关闭程序的代码片段:
private void exit2() {
ActivityManager actMgr = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
actMgr.restartPackage(getPackageName()); }
调用上述方法就能彻底地关闭掉程序,一般仅仅调用finish()是无法彻底关闭程序的。 但要注意一点,调用系统服务需要在AndroidManifest.xml文件中增加权限。
相关文章推荐
- 一个面试题引发的思考:Android应用退出时候,关闭所有的Activity
- Android 长按home键强制关闭应用后,在哪里执行退出应用?
- Android关闭应用中的所有Activity(一)
- Android应用关闭,重启
- android关闭应用
- android系统 关闭应用
- Android关闭应用中的所有Activity(一)
- 两种方法关闭android应用
- 检测Android应用(APP)的启动与关闭
- Android从一个Activity中关闭整个应用
- Android关闭应用的三种办法
- android应用关闭本身(自杀)
- android 应用重启 关闭
- 谷歌计划远程关闭Android设备上恶意应用
- [Android分享] 关闭正在运行的应用(精华板)
- android-关闭应用
- Android应用的彻底关闭
- android 如何彻底关闭应用
- Android 一次性关闭所有的activity 完全退出应用
- android 关闭应用的代码