Android版本更新(适用于6.0/7.0)

时间:2025-03-21 07:30:13
public class DownLoadServerice extends Service { /**广播接受者*/ private BroadcastReceiver receiver; /**系统下载管理器*/ private DownloadManager dm; /**系统下载器分配的唯一下载任务id,可以通过这个id查询或者处理下载任务*/ private long enqueue; private String downloadUrl=""; //下载地址 @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { install(context); //销毁当前的Service stopSelf(); } }; registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); //下载需要写SD卡权限, targetSdkVersion>=23 需要动态申请权限 (this) // 申请权限 .request(.WRITE_EXTERNAL_STORAGE) .subscribe(new Action1<Boolean>() { @Override public void call(Boolean granted) { if(granted){ //请求成功 startDownload(downloadUrl); }else{ // 请求失败回收当前服务 stopSelf(); } } }); return Service.START_STICKY; } /** * 通过隐式意图调用系统安装程序安装APK */ public static void install(Context context) { File file = new File( (Environment.DIRECTORY_DOWNLOADS) , ""); Intent intent = new Intent(Intent.ACTION_VIEW); // 由于没有在Activity环境下启动Activity,设置下面的标签 (Intent.FLAG_ACTIVITY_NEW_TASK); if(.SDK_INT>=24) { //判读版本是否在7.0以上 //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致 参数3 共享的文件 Uri apkUri = (context, "", file); //添加这一句表示对目标应用临时授权该Uri所代表的文件 (Intent.FLAG_GRANT_READ_URI_PERMISSION); (apkUri, "application/-archive"); }else{ ((file), "application/-archive"); } (intent); } @Override public void onDestroy() { //服务销毁的时候 反注册广播 unregisterReceiver(receiver); super.onDestroy(); } private void startDownload(String downUrl) { //获得系统下载器 dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); //设置下载地址 request = new ((downUrl)); //设置下载文件的类型 ("application/-archive"); //设置下载存放的文件夹和文件名字 (Environment.DIRECTORY_DOWNLOADS, ""); //设置下载时或者下载完成时,通知栏是否显示 (.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); ("下载新版本"); //执行下载,并返回任务唯一id enqueue = (request); } }