Android APK安装完成自动删除安装包
需要实现此功能,一般实际开发是在自动版本更新上,当更新完开始自动安装完毕后,删除内存卡里的安装包。实现方式很简单,监听应用广播,获取内存卡下的文件,删除!
1、监听广播
- package com.example.a75213.testdownloaddemo;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.widget.Toast;
- import com.example.a75213.testdownloaddemo.contant.comm;
- /**
- * Created by 75213 on 2017/11/7.
- */
- public class InitApkBroadCastReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
- comm.rmoveFile("http://imtt.dd.qq.com/16891/7C7BB50B68B684A36339AF1F615E2848.apk");
- Toast.makeText(context , "监听到系统广播添加" , Toast.LENGTH_LONG).show();
- }
- if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
- comm.rmoveFile("http://imtt.dd.qq.com/16891/7C7BB50B68B684A36339AF1F615E2848.apk");
- Toast.makeText(context , "监听到系统广播移除" , Toast.LENGTH_LONG).show();
- System.out.println("");
- }
- if (Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())) {
- comm.rmoveFile("http://imtt.dd.qq.com/16891/7C7BB50B68B684A36339AF1F615E2848.apk");
- Toast.makeText(context , "监听到系统广播替换" , Toast.LENGTH_LONG).show();
- }
- }
- }
2、记得给删除权限和广播注册【AndroidMainifest】
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <receiver
- android:name=".InitApkBroadCastReceiver"
- android:enabled="true">
- <intent-filter>
- <action android:name="android.intent.action.PACKAGE_ADDED" />
- <action android:name="android.intent.action.PACKAGE_REPLACED" />
- <action android:name="android.intent.action.PACKAGE_REMOVED" />
- <data android:scheme="package" />
- </intent-filter>
- </receiver>
- package com.example.a75213.testdownloaddemo.contant;
- import android.os.Environment;
- import java.io.File;
- /**
- * Created by 75213 on 2017/11/1.
- */
- public class comm{
- public static File getPathFile(String path){
- String apkName = path.substring(path.lastIndexOf("/"));
- File outputFile = new File(Environment.getExternalStoragePublicDirectory
- (Environment.DIRECTORY_DOWNLOADS), apkName);
- return outputFile;
- }
- public static void rmoveFile(String path){
- File file = getPathFile(path);
- file.delete();
- }
- }