app实现自动升级

每开发一款app都要升级版本,下面就简述一下app的自动升级,希望能帮助到大家。

1、先声明一个服务类,实现自动下载的功能。

public class UpdateService extends Service {

   public UpdateService() {  
       
    }  
    /** 安卓系统下载类 **/  
    DownloadManager manager;  
  
    /** 接收下载完的广播 **/  
    DownloadCompleteReceiver receiver;  
  
    /** 初始化下载器 **/  
    private void initDownManager(String url) {  
  
        manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);  
  
        receiver = new DownloadCompleteReceiver();  
  
        //设置下载地址  
//        String urlPath = url;  
        Uri parse = Uri.parse(url);  
        DownloadManager.Request down = new DownloadManager.Request(parse);  
  
//     百度音乐           Uri.parse("http://gdown.baidu.com/data/wisegame/fd84b7f6746f0b18/baiduyinyue_4802.apk"));
  
        // 设置允许使用的网络类型,这里是移动网络和wifi都可以  
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);  
  
        // 下载时,通知栏显示途中  
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {  
            down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);  
        }  
  
        // 显示下载界面  
        down.setVisibleInDownloadsUi(true);  
  
        // 设置下载后文件存放的位置  
  
  
        String apkName = parse.getLastPathSegment();  
        down.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, apkName);  
  
        // 将下载请求放入队列  
        manager.enqueue(down);  
  
        //注册下载广播  
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));  
    }  
  
    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
  
        // 调用下载  
        initDownManager(intent.getStringExtra("url"));  
  
        return super.onStartCommand(intent, flags, startId);  
    }  
  
    @Override  
    public IBinder onBind(Intent intent) {  
  
        return null;  
    }  
  
    @Override  
    public void onDestroy() {  
  
        // 注销下载广播  
        if (receiver != null)  
            unregisterReceiver(receiver);  
  
        super.onDestroy();  
    }  
  
    // 接受下载完成后的intent  
    class DownloadCompleteReceiver extends BroadcastReceiver {  
  
        @Override  
        public void onReceive(Context context, Intent intent) {  
  
            //判断是否下载完成的广播  
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {  
                //获取下载的文件id  
                long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);  
                Log.e("tag","下载id="+downId);  
  
                //自动安装apk  
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {  
                    Uri uriForDownloadedFile = manager.getUriForDownloadedFile(downId);  
                    Log.e("tag","uri="+uriForDownloadedFile);  
                    installApkNew(uriForDownloadedFile);  
                }  
  
                //停止服务并关闭广播  
                UpdateService.this.stopSelf();  
  
            }  
        }  
  
        //安装apk  
        protected void installApkNew(Uri uri) {  
            Intent intent = new Intent();  
            //执行动作  
            intent.setAction(Intent.ACTION_VIEW);  
            //执行的数据类型  
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
            intent.setDataAndType(uri, "application/vnd.android.package-archive");  
            //不加下面这句话是可以的,查考的里面说如果不加上这句的话在apk安装完成之后点击单开会崩溃  
            // android.os.Process.killProcess(android.os.Process.myPid());  
            try {  
                startActivity(intent);  
            }catch (Exception e){  
                e.printStackTrace();  
            }  
        }  
    }  

}

2、在AndroidManifest里配置服务

  <service
   android:name=".UpdateService"
   android:exported="false"
   />

3、通过请求接口,来获取下载链接和versioncode,再通过versioncode和已安装版本的versioncode进行比较处理。

 if(data.getInt("current_version_code")>DevicesUtil.getVersionCode(MainActivity.this)){
    startUpdate(app_url);
 }

4、通过比较versioncode来启动服务来进行下载


 public void startUpdate(final String url){
    new Thread(new Runnable() {
        @Override
        public void run() {
            //启动服务
            Intent service = new Intent(MainActivity.this,UpdateService.class);
            service.putExtra("url",url);
            startService(service);
        }
    }).start();

 }

5、获取已安装版本的versioncode

public static int getVersionCode(Context context) {
   int versionCode = 1;
   try {
      PackageManager packageManager = context.getPackageManager();
      PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
      versionCode = packInfo.versionCode;
   } catch (Exception e) {
      e.printStackTrace();
   }
   return versionCode;
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值