android卸载提示的思路是启动一个服务监控android系统的打印日志,当监控到"android.intent.action.DELETE"并且包含自己应用的包名时,提示给用户。
上面的代码基本实现了卸载提示,最后不要忘了权限:
代码下载地址:
采用服务(实现接口处理handleLog)后台允许 启动一个线程监控日志 调用接口handleLog处理日志
package edu.nedu.uninstalldemo;
public interface LogcatObserver {
public void handleLog(String line);
}
监控代码
- public class AndroidLogcatScannerThread extends Thread {
- private LogcatObserver observer;
- public AndroidLogcatScannerThread(LogcatObserver observer) {
- this.observer = observer;
- }
- public void run() {
- String[] cmds = { "logcat", "-c" };
- String shellCmd = "logcat";
- Process process = null;
- InputStream is = null;
- DataInputStream dis = null;
- String line = "";
- Runtime runtime = Runtime.getRuntime();
- try {
- //TODO step2 流读取日志信息 调用接口方法回掉处理
- observer.handleLog(line);
- int waitValue;
- waitValue = runtime.exec(cmds).waitFor();
- observer.handleLog("waitValue=" + waitValue + "\n Has do Clear logcat cache.");
- process = runtime.exec(shellCmd);
- is = process.getInputStream();
- dis = new DataInputStream(is);
- while ((line = dis.readLine()) != null) {
- //Log.d("Log","Log.Bestpay:"+line);
- if(observer!=null)
- observer.handleLog(line);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (IOException ie) {
- ie.printStackTrace();
- } finally {
- try {
- if (dis != null) {
- dis.close();
- }
- if (is != null) {
- is.close();
- }
- if (process != null) {
- process.destroy();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
监控服务:
- public class AndroidLogcatScannerService extends Service implements LogcatObserver{
- @Override
- public void onCreate() {
- // TODO Auto-generated method stub
- super.onCreate();
- }
- @Override
- public void onDestroy() {
- // TODO Auto-generated method stub
- super.onDestroy();
- }
- @Override
- public void onStart(Intent intent, int startId) {
- // TODO Auto-generated method stub
- super.onStart(intent, startId);
- //TODO step1 启动监控日志线程
- AndroidLogcatScannerThread scannerThread=new AndroidLogcatScannerThread(AndroidLogcatScannerService.this);
- scannerThread.start();
- }
- @Override
- public IBinder onBind(Intent intent) {
- // TODO Auto-generated method stub
- return null;
- }
- @Override
- public void handleLog(String info) {
- //TODO step3 处理日志数据
- if (info.contains("android.intent.action.DELETE") && info.contains(getPackageName())) {
- Intent intent = new Intent();
- intent.setClass(AndroidLogcatScannerService.this, UninstallActivity.class);
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- startActivity(intent);
- }
- }
- }
上面的代码基本实现了卸载提示,最后不要忘了权限:
- <uses-permission android:name="android.permission.READ_LOGS"></uses-permission>
代码下载地址: