android实现 彻底退出应用/清除数据/卸载应用的方法

清楚应用数据和卸载应用,直接执行命令:

* String cmd = "pm clear " + packageName; 或者 * String cmd = "pm clear " + packageName  + " HERE";

* String cmd = "pm uninstall " + packageName; 或者 * String cmd = "pm uninstall " + packageName  + " HERE";

* String cmd = "pm install " + apk_path; 或者 * String cmd = "pm uninstall " + apk_path+ " HERE";

且在清楚数据之后应用本身的Service和Alarm定时会自动取消掉,进程也随之结束, 以此类推adb所有命令都可以这样执行。


package com.app.exit.demo;


import java.io.IOException;


import android.util.Log;


/**
 * 运行命令管理器
 * 等同于在PC端adb shell之后执行命令,pm clear packageName
 * 但是只能回自己操作,不能清除其他应用的数据;
 * 卸载其他应用(限root设备或者厂商提供接口)
 * @author hulk
 *
 */
public class RuntimeCmdManager {


private static final String TAG = "RuntimeCmdManager";


/**
* 清除应用缓存的用户数据,同时停止所有服务和Alarm定时task
* String cmd = "pm clear " + packageName;
* String cmd = "pm clear " + packageName  + " HERE";
* Runtime.getRuntime().exec(cmd)
* @param packageName
* @return
*/
public static Process clearAppUserData(String packageName) {
Process p = execRuntimeProcess("pm clear " + packageName);
if (p == null) {
LogTag.log("Clear app data packageName:" + packageName
+ ", FAILED !");
} else {
LogTag.log("Clear app data packageName:" + packageName
+ ", SUCCESS !");
}
return p;
}


/**
* 卸载应用,只能对root设备有效
* String cmd = "pm uninstall " + packageName;
* Runtime.getRuntime().exec("pm uninstall " + packageName)
* @param packageName
* @return
*/
public static Process uninstallApp(String packageName) {
Process p = execRuntimeProcess("pm uninstall " + packageName);
if (p == null) {
LogTag.log("Uninstall app packageName:" + packageName + ", FAILED !");
} else {
LogTag.log("Uninstall app packageName:" + packageName + ", SUCCESS !");
}
return p;
}


public static Process execRuntimeProcess(String commond) {
Process p = null;
try {
p = Runtime.getRuntime().exec(commond);
} catch (IOException e) {
LogTag.log("exec Runtime commond:" + commond + ", IOException" + e);
e.printStackTrace();
}
LogTag.log("exec Runtime commond:" + commond + ", Process:" + p);
return p;
}
}


彻底退出应用,不清除数据的方法:

停止应用中所有Service。调用ActivityManager.killBackgroundProcesses(packageName);

示例:

package com.app.exit.demo;


import java.util.List;


import android.support.v7.app.ActionBarActivity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {


private static final String TAG = "MainActivity";
public static final int ALARM_INTERVAL_MILLIS = 10 * 1000;


TextView mMsgTv;
Button exitAppBtn;


List runningServices;
ActivityManager mActivityManager;
List packageInfos;
ServiceInfo[] serviceInfos;
AlarmManager mAlarmManager;
private PendingIntent operation;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMsgTv = (TextView) findViewById(R.id.msg_tv);
exitAppBtn = (Button) findViewById(R.id.btn_exit_app);
exitAppBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
LogTag.i("" + this);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mActivityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
startServices();
runningServices = mActivityManager.getRunningServices(10000);
// proccessRunningServices(false);
packageInfos = getPackageManager().getInstalledPackages(
PackageManager.GET_SERVICES);
processPackageInfos(false);
setRepeating();
}


/**
* 定时启动SecondActivity,清除自身数据或者卸载
*/
private void setRepeating() {
if (operation == null) {
operation = getSecondPendingIntent();
}
long startTime = System.currentTimeMillis() + ALARM_INTERVAL_MILLIS;
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime,
ALARM_INTERVAL_MILLIS, operation);
}


private PendingIntent getSecondPendingIntent() {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
PendingIntent operation = PendingIntent.getActivity(
getApplicationContext(), 0, intent, 0);
return operation;
}


private void startServices() {
startService(new Intent(this, MyService1.class));
startService(new Intent(this, MyService2.class));
}


private void processPackageInfos(boolean isStop) {
for (PackageInfo pinfo : packageInfos) {
if (getPackageName().equals(pinfo.packageName)) {
serviceInfos = pinfo.services;
for (ServiceInfo sinfo : serviceInfos) {
if (isStop) {
boolean result = stopPackageService(this,
getPackageName(), sinfo.name);
Log.w(TAG, "Stop sinfo.name: " + sinfo.name
+ ", result=" + result);
} else {
Log.d(TAG, "sinfo.name: " + sinfo.name);
}
}
}
}
}


private void proccessRunningServices(boolean isStop) {
if (runningServices == null) {
Log.w(TAG, "runningServices is null !! ");
return;
}


for (RunningServiceInfo runningServiceInfo : runningServices) {
String serviceName = runningServiceInfo.service.getClassName();
String process = runningServiceInfo.process;
if ("com.app.exit.demo".equals(process)) {
if (isStop) {
boolean result = stopPackageService(getApplication(),
getPackageName(), serviceName);
Log.w(TAG, "stopService " + serviceName + ", result= "
+ result);
} else {
Log.i(TAG, "runningServiceInfo.process=" + process
+ ",runningServiceInfo.pid="
+ runningServiceInfo.pid
+ ", runningServiceInfo.getClass=" + serviceName);
}
}
}
}


private boolean stopPackageService(Context context, String packageName,
String serviceName) {
Intent service = new Intent();
service.setClassName(packageName, serviceName);
return context.stopService(service);
}


@Override
protected void onDestroy() {
super.onDestroy();
killProcess();
LogTag.i("onDestroy: " + this);
}

private void killProcess() {
// proccessRunningServices(true);
processPackageInfos(true);
String packageName = getPackageName();
mActivityManager.killBackgroundProcesses(packageName);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

注意Manifest配置:



    package="com.app.exit.demo"
    android:versionCode="1"
    android:versionName="1.0" >


            android:minSdkVersion="8"
        android:targetSdkVersion="21" />


   


            android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
                    android:name=".MainActivity"
            android:label="@string/app_name" >
           
               


               
           

       
                    android:name=".SecondActivity"
            android:label="SecondActivity"
            android:launchMode="singleTask" >
       


       
       
   







你可能感兴趣的:(Android,java)