Android 結束進程的方法


Android 結束進程,關閉程序的方法,經過這幾天的調研,發現了Android結束一個進程的方法

即採用下面這個類

void android.app.ActivityManager.restartPackage(String packageName)

public void restartPackage (String packageName)

使用這個類的具體源代碼

Java代碼 

final ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);    
am.restartPackage(getPackageName()); 
再加上uses-permission
<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);       
manager.killBackgroundProcesses(getPackageName());  

//需要在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);

需要在manifest里加上shareduid定義

  1. android:sharedUserId="android.uid.system"  
 

 

另外加上權限

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

並且採用系統platform簽名


因爲需要用FORCE_STOP_PACKAGES權限,該權限只賦予系統簽名級程序

 

即可實現強制停止指定程序

 

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章