天天看點

Android程序與線程基本知識四

4.android中如何結束程序

android 結束程序,關閉程式的方法 即采用下面這個類

void android.app.activitymanager.restartpackage(string packagename)

public void restartpackage (string packagename)

since: api level 3

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 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 restart_packages to be able to call this method. parameters packagename the name of the package to be stopped.

使用這個類的具體源代碼

final activitymanager am = (activitymanager)getsystemservice(context.activity_service);

am.restartpackage(getpackagename());

不要忘記了在配置檔案中設定權限:

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

結束程序還有

android.os.process.killprocess(pid)隻能終止本程式的程序,無法終止其它的

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.

public void finish ()

call this when your activity is done and should be closed. the activityresult is propagated back to whoever launched you via onactivityresult().

這是結束目前activity的方法 在android2.2版本之後則不能再使用restartpackage()方法,而應該使用killbackgroundprocesses()方法

manager.killbackgroundprocesses(getpackagename());

activitymanager manager = (activitymanager)getsystemservice(activity_service);

//需要在xml中加入權限聲明

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

另外,在android2.2以後,如果服務在ondestroy裡加上了start自己,用kill backgroudprocess通常無法結束自己。

還有一種最新發現的方法,利用反射調用forcestoppackage來結束程序

method forcestoppackage = am.getclass().getdeclaredmethod("forcestoppackage", string.class);

forcestoppackage.setaccessible(true);

forcestoppackage.invoke(am, yourpkgname);

配置檔案中需要添加定義:

android:shareduserid="android.uid.system"

另外需要再在配置檔案添權重限:

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

并且采用系統platform簽名 因為需要用force_stop_packages權限,該權限隻賦予系統簽名級程式 即可實作強制停止指定程式

還有一種方法 利用linux的kill -9指令

完畢。^_^

打賞

<b></b>贊

<b></b>收藏

<b></b>評論

分享

微網誌

qq

微信

Android程式與線程基本知識四

舉報

上一篇:android程序與線程基本知識三

下一篇:listview 滾動翻頁/滾動加載(類似qq空間滾動加載頁面)

android程序與線程基本知識,android程序與線程基本知識二,android程序與線程基本知識一,android程序與線程基本知識三,線程的基本知識,css基本知識介紹,hbase基本知識,javaweb基本知識,java基本知識,java線程的基本知識