美文网首页程序员
Android版本后台更新完成后自动安装

Android版本后台更新完成后自动安装

作者: 永远爱你ol | 来源:发表于2020-11-27 11:09 被阅读0次

    分享一下在工作中遇到的Android版本后台更新后自动安装的功能,在网上找了好多资料,然后自己修改,写了一个比较完整的版本。

    一、判断当前版本号

    //获取本地版本号
      public  String getVersion() {
        try {
              PackageManager manager =activity.getPackageManager();
              PackageInfo info =manager.getPackageInfo(activity.getPackageName(),0);
              String version = info.versionName;
              return version;
              }catch (Exception e) {
                 e.printStackTrace();
                 return "0";
              }
          }
    

    接下来是本地版本号和服务器的版本号进行对比

      public  int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
          return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        while (index < minLen
          && (diff = Integer.parseInt(version1Array[index])
          - Integer.parseInt(version2Array[index])) == 0) {
          index++;
        }
        if (diff == 0) {
          for (int i = index; i < version1Array.length; i++) {
            if (Integer.parseInt(version1Array[i]) > 0) {
              return 1;
            }
          }
          for (int i = index; i < version2Array.length; i++) {
            if (Integer.parseInt(version2Array[i]) > 0) {
              return -1;
            }
          }
          return 0;
        } else {
          return diff > 0 ? 1 : -1;
        }
      }
    

    二、创建一个更新服务的service

      public class UpdateService extends Service {
      public StringDOWNLOAD_PATH = Environment.getExternalStorageDirectory()                      +"/Download/Anxin.apk";
        private Stringurl;//下载链接
        private long refernece;
        private BroadcastReceiverreceiver;
        private IntentFilterfilter;
        public IBinder onBind(Intent arg0) {
          return null;
    }
    
    @Override
      public void onCreate() {
          super.onCreate();
    }
    
    @Override
      public int onStartCommand(Intent intent,int flags,int startId) {
        if (intent !=null) {
        url = intent.getStringExtra("Key_Down_Url");
        if (url !=null && !TextUtils.isEmpty(url)) {
        download(url);
          }
      }
        return super.onStartCommand(intent, flags, startId);
    }
    
    public void download(String url) {
        if (new File(DOWNLOAD_PATH).exists()) {
          new File(DOWNLOAD_PATH).delete();
        }
        receiver();
        DownloadManager dManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
       request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Anxin.apk");
        request.setDescription("新版本下载中...");
        request.setTitle("版本更新");
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setMimeType("application/vnd.android.package-archive");
        // 设置为可被媒体扫描器
        request.allowScanningByMediaScanner();
        // 设置为可见
        request.setVisibleInDownloadsUi(true);
        try {
          refernece = dManager.enqueue(request);
        } catch (Exception e) {
        }
      }
    
      public void receiver() {
        filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        receiver = new BroadcastReceiver() {
          public void onReceive(Context context, Intent intent) {
            long myDwonloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (refernece == myDwonloadID) {
              DownloadManager dManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
              setPermission(DOWNLOAD_PATH);
              Intent install = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()));
              install.setAction(Intent.ACTION_VIEW);
              install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              install.addCategory(Intent.CATEGORY_DEFAULT);
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//大于Android版本7.0
                //这里的"com.anxin.provider"需要和AndroidManifest.xml的provider属性保持一致
                Uri contentUri = FileProvider.getUriForFile(context, "com.anxin.provider", new File(DOWNLOAD_PATH));
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                install.setDataAndType(contentUri, "application/vnd.android.package-archive");
                context.startActivity(install);
              } else {
                try {
                  Uri downloadFileUri = dManager.getUriForDownloadedFile(refernece);
                  install.setDataAndType(downloadFileUri.fromFile(new File(DOWNLOAD_PATH)), "application/vnd.android.package-archive");
                  context.startActivity(install);
                } catch (RuntimeException e) {
                  e.printStackTrace();
                }
              }
            }
          }
        };
        registerReceiver(receiver, filter);
      }
    
     /**
       * 提升读写权限
       *
       * @param filePath 文件路径
       */
        public static void setPermission(String filePath) {
        String command ="chmod " +"777" +" " + filePath;
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(command);
        }catch (IOException e) {
            e.printStackTrace();
          }
      }
    
      public void onDestroy() {
        unregisterReceiver(receiver);
      }
    }
    

    三、接下来就是通过弹框进行更新

        public void AlertDialog2() {
           mDialog =new Dialog(SheZhiActivity.this, R.style.mydialog);
           View view = View.inflate(SheZhiActivity.this, R.layout.view_dialog,null);
           mDialog.setContentView(view);
           TextView UpdateContent = (TextView)view.findViewById(R.id.UpdateContent);
           UpdateContent.setText(downContent);
           TextView UpdateVersion = (TextView)view.findViewById(R.id.UpdateVersion);
           UpdateVersion.setText("V"+newVersion);
           mDialog.getWindow().findViewById(R.id.UpdateNow).setOnClickListener(new View.OnClickListener() {
        @Override
           public void onClick(View v) {
           Intent intent =new Intent(SheZhiActivity.this, UpdateService.class);
           intent.putExtra("Key_Down_Url",downUrl);
           startService(intent);
           Toast.makeText(getApplicationContext(),"后台更新下载中...",  Toast.LENGTH_SHORT).show();
           mDialog.dismiss();
        }
    });
           mDialog.show();
    }
    

    四、需要在AndroidManifest.xml中添加provider

       <provider
          android:name="android.support.v4.content.FileProvider"
          android:authorities="com.anxin.provider"
          android:exported="false"
          android:grantUriPermissions="true">
          <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
        </provider>
    

    五、总结

    在android版本6.0之前和之后的安装方式是不同的,需要注意一下。最后别忘了在AndroidManifest.xml中添加各种权限。

    相关文章

      网友评论

        本文标题:Android版本后台更新完成后自动安装

        本文链接:https://www.haomeiwen.com/subject/pgfxwktx.html