Android Apk安装包断点下载 实现更新

最近因为自己的公司项目 需要改成apk断点下载apk

我们原来没这个需要,因经理要求 给客户更好的体验,开发断点下载apk,还好小哥之前搞过这个,手拿把掐的把这个功能实现了。下面不多说 先上个成果视频。

cc8b

网络请求依赖

implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
//网络请求框架 retrofit
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'

第一步,创建网络请求类和网络接口下载回调

public class RetrofitHttp {

    private static final int DEFAULT_TIMEOUT = 10;
    private static final String TAG = "RetrofitClient";

    private ApiService apiService;

    private OkHttpClient okHttpClient;

    public static String baseUrl = ApiService.BASE_URL;

    private static RetrofitHttp sIsntance;

    public static RetrofitHttp getInstance(String Url) {
        if (sIsntance == null) {
            synchronized (RetrofitHttp.class) {
                if (sIsntance == null) {
                    sIsntance = new RetrofitHttp(Url);
                }
            }
        }
        return sIsntance;
    }

    private RetrofitHttp(String Url) {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(Url)
                .build();
        apiService = retrofit.create(ApiService.class);
    }

    public void downloadFile(final long range, final String url, final String fileName, final DownloadCallBack downloadCallback) {
        //断点续传时请求的总长度
        File file = new File(Constant.APP_ROOT_PATH + Constant.DOWNLOAD_DIR, fileName);
        String totalLength = "-";
        if (file.exists()) {
            totalLength += file.length();
        }

        apiService.executeDownload("bytes=" + Long.toString(range) + totalLength, url)
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        DownloadIntentService.compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        RandomAccessFile randomAccessFile = null;
                        InputStream inputStream = null;
                        long total = range;
                        long responseLength = 0;
                        try {
                            byte[] buf = new byte[2048];
                            int len = 0;
                            responseLength = responseBody.contentLength();
                            inputStream = responseBody.byteStream();
                            String filePath = Constant.APP_ROOT_PATH + Constant.DOWNLOAD_DIR;
                            File file = new File(filePath, fileName);
                            File dir = new File(filePath);
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            randomAccessFile = new RandomAccessFile(file, "rwd");
                            if (range == 0) {
                                randomAccessFile.setLength(responseLength);
                            }
                            randomAccessFile.seek(range);

                            int progress = 0;
                            int lastProgress = 0;

                            while ((len = inputStream.read(buf)) != -1) {
                                randomAccessFile.write(buf, 0, len);
                                total += len;
                                SPDownloadUtil.getInstance().save(url, total);
                                lastProgress = progress;
                                progress = (int) (total * 100 / randomAccessFile.length());
                                if (progress > 0 && progress != lastProgress) {
                                    downloadCallback.onProgress(progress);
                                }
                            }
                            downloadCallback.onCompleted();
                        } catch (Exception e) {
                            Log.d(TAG, e.getMessage());
                            downloadCallback.onError(e.getMessage());
                            e.printStackTrace();
                        } finally {
                            try {
                                if (randomAccessFile != null) {
                                    randomAccessFile.close();
                                }

                                if (inputStream != null) {
                                    inputStream.close();
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        downloadCallback.onError(e.toString());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
}

网络接口下载回调

public interface DownloadCallBack {

    void onProgress(int progress);

    void onCompleted();

    void onError(String msg);
}

第二步,创建请求接口

public interface ApiService {
    //这是域名
    public static final String BASE_URL = "http://xxxxxxxxx:xxxxxx";
    @Streaming
    @GET
    Observable<ResponseBody> executeDownload(@Header("Range") String range, @Url() String url);

}

第三步,创建Service提供下载服务 DownloadIntentService继承IntentService    清单文件里别忘记注册

public class DownloadIntentService extends IntentService {
    private Context mContext;
    private static final String TAG = "DownloadIntentService";
    private NotificationManager mNotifyManager;
    private String mDownloadFileName;
    private Notification mNotification;
    public static CompositeDisposable compositeDisposable = new CompositeDisposable();
    public DownloadIntentService() {
        super("InitializeService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        String downloadUrl = intent.getExtras().getString("download_url");
        final int downloadId = intent.getExtras().getInt("download_id");
        mDownloadFileName = intent.getExtras().getString("download_file");
        String Url = intent.getExtras().getString("url");
        Log.d(TAG, "download_url --" + downloadUrl);
        Log.d(TAG, "download_file --" + mDownloadFileName);

        final File file = new File(Constant.APP_ROOT_PATH + Constant.DOWNLOAD_DIR + mDownloadFileName);
        long range = 0;
        int progress = 0;
        if (file.exists()) {
            range = SPDownloadUtil.getInstance().get(downloadUrl, 0);
            progress = (int) (range * 100 / file.length());
            if (range == file.length()) {
                Intent intents = new Intent("com.inwish.downloaddemoapk");
                intents.putExtra("installApp",  true+"");
                intents.putExtra("file",  file+"");
                sendBroadcast(intents);
                return;
            }
        }
        Log.d(TAG, "range = " + range);
        RetrofitHttp.getInstance(Url).downloadFile(range, downloadUrl, mDownloadFileName, new DownloadCallBack() {
            @Override
            public void onProgress(int progress) {
                Log.e("已经下载==","已下载" + progress + "%");
                Intent intent = new Intent("com.inwish.downloaddemoapk");
                intent.putExtra("progress",  progress+"");
                intent.putExtra("installApp",  false+"");
                intent.putExtra("file",  file+"");
                sendBroadcast(intent);
            }

            @Override
            public void onCompleted() {
                Log.d(TAG, "下载完成"+  Md5Utils.getFileMD5(file));
                SPDownloadUtil.getInstance().save("md5", Md5Utils.getFileMD5(file));
                Intent intent = new Intent("com.inwish.downloaddemoapk");
                intent.putExtra("installApp",  true+"");
                intent.putExtra("file",  file+"");
                sendBroadcast(intent);
//                SPDownloadUtil.getInstance().clear();

            }

            @Override
            public void onError(String msg) {
                Log.d(TAG, "下载发生错误--" + msg);
            }
        });
    }

    public void setCompositeDisposable() {
        //暂停下载
        if (!compositeDisposable.isDisposed()) {
            if (compositeDisposable.size() != 0) {
                compositeDisposable.clear();
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}

第四步,创建文件存储路径 

public class Constant {
    public final static String APP_ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + MainApplication.getInstance().getPackageName();
    public final static String DOWNLOAD_DIR = "/downlaod/";
}

第五步,因为我在我本地加了MD5判断下载的apk是否和网上的一致 所以我这里加了一个MD5的工具类

public class Md5Utils {
    protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    public synchronized static String getFileMD5(File file) {
        if (!file.exists() || !file.isFile()) {
            System.out.println("文件不存在");
            return null;
        }
        MessageDigest digest = null;
        FileInputStream fis = null;
        try {
            digest = MessageDigest.getInstance("MD5");
            fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int numRead = 0;
            while ((numRead = fis.read(buffer)) > 0) {
                digest.update(buffer, 0, numRead);
            }
            fis.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return bufferToHex(digest.digest());
    }
    private static String bufferToHex(byte bytes[]) {
        return bufferToHex(bytes, 0, bytes.length);
    }
    private static String bufferToHex(byte bytes[], int m, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }
    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = hexDigits[(bt & 0xf0) >> 4];
        char c1 = hexDigits[bt & 0xf];
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }
}

因为咱们是要把apk文件下载到手机内存里的 所以由于android 文件权限隐私  需要声明Provider

我这里自定义MyProvider

public class MyProvider extends FileProvider {
}

并在清单文件里注册

<provider
    android:name=".util.MyProvider"
    android:authorities="包名.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">

    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"
        />
</provider>

第六步,创建存储工具类

public class SPDownloadUtil {

    private static SharedPreferences mSharedPreferences;
    private static SPDownloadUtil instance;

    private SPDownloadUtil() {
    }

    public static SPDownloadUtil getInstance() {
        if (mSharedPreferences == null || instance == null) {
            synchronized (SPDownloadUtil.class) {
                if (mSharedPreferences == null || instance == null) {
                    instance = new SPDownloadUtil();
                    mSharedPreferences = MainApplication.getInstance().getSharedPreferences(MainApplication.getInstance().getPackageName() + ".downloadSp", Context.MODE_PRIVATE);
                }
            }
        }
        return instance;
    }

    /**
     * 清空数据
     *
     * @return true 成功
     */
    public boolean clear() {
        return mSharedPreferences.edit().clear().commit();
    }

    /**
     * 保存数据
     *
     * @param key   键
     * @param value 保存的value
     */
    public boolean save(String key, long value) {
        return mSharedPreferences.edit().putLong(key, value).commit();
    }
    public boolean save(String key, String value) {
        return mSharedPreferences.edit().putString(key, value).commit();
    }
    /**
     * 获取保存的数据
     *
     * @param key      键
     * @param defValue 默认返回的value
     * @return value
     */
    public long get(String key, long defValue) {
        return mSharedPreferences.getLong(key, defValue);
    }
    public String get(String key, String defValue) {
        return mSharedPreferences.getString(key, defValue);
    }
}

创建Application

public class MainApplication extends Application {
    private static MainApplication sInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
    }

    public static Context getInstance() {
        return sInstance;
    }
}

断点下载,肯定开权限啊  这点大家就不用我多说了吧  自行百度

第七步,创建AppDownloadManager

    在AppDownloadManager创建一个广播 监听下载的进度

   

    private final BroadcastReceiver reciver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!intent.getStringExtra("installApp").equals("true")) {
                mPrecent.setText(intent.getStringExtra("progress") + " %");
                mProgressBar.setProgress(Integer.parseInt(intent.getStringExtra("progress")));
                if (Integer.parseInt(intent.getStringExtra("progress")) == 100) {
                    mDialog1.dismiss();
                }
            } else {
                Log.e("广播已经下载==", "已下载" + new File(intent.getStringExtra("file")));
                installApp(new File(intent.getStringExtra("file")));
            }
        }
    };

广播下载完成 去安装

 private void installApp(File apkFile) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uriForFile = FileProvider.getUriForFile(mContext, "com.inwish.downloaddemoapk.fileprovider", apkFile);
            install.setDataAndType(uriForFile, "application/vnd.android.package-archive");
        } else {
            install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }

        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.unregisterReceiver(reciver);
        mContext.startActivity(install);
    }

下面关键来了   调用的地方来了  大家看好

private static final int DOWNLOADAPK_ID = 10; 

mContext.registerReceiver(reciver, new IntentFilter("com.inwish.downloaddemoapk"));
                        //弹出进度条,先隐藏前一个dialog
                        if (isServiceRunning(DownloadIntentService.class.getName())) {
                            Toast.makeText(mContext, "正在下载", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String downloadUrl = "xx/xx.apk";//这里是接口名 拼到域名后面的
                        Intent intent = new Intent(mContext, DownloadIntentService.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("download_url", downloadUrl);
                        bundle.putString("url","域名");
                        bundle.putInt("download_id", DOWNLOADAPK_ID);
                        bundle.putString("download_file", "xx.apk");
                        intent.putExtras(bundle);
                        mContext.startService(intent);
                        dialog.dismiss();

这里有一个判断服务是否开启防止用户连续点击 下载造成服务器拥堵isServiceRunning

/**
     * 用来判断服务是否运行.
     *
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    private boolean isServiceRunning(String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(Integer.MAX_VALUE);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

以上就完成了   https://download.csdn.net/download/qq_28132377/88011271 demo在此 欢迎大家来下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值