【网学网提醒】:本文主要为网学会员提供Android自动更新,希望对需要Android自动更新网友有所帮助,学习一下!
Android实现自动更新项目结构如下图所示
新建一个负责检测更新的Activity
publicclassMainAcitivityextendsActivity{privateUpdateManagermUpdateManager;@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);//这里来检测版本是否需要更新mUpdateManager=newUpdateManager(this);mUpdateManager.checkUpdateInfo();}}
新建一个负责软件更新功能模块
UpdateManager.java下载应用
程序然后安装//选择下载builder.setPositiveButton("
下载",newOnClickListener(){@OverridepublicvoidonClick(DialogInterfacedialog,intwhich){dialog.dismiss();showDownloadDialog();}});
//显示软件版本更新对话框privatevoidshowDownloadDialog(){AlertDialog.Builderbuilder=newBuilder(mContext);builder.setTitle("软件版本更新");finalLayoutInflaterinflater=LayoutInflater.from(mContext);Viewv=inflater.inflate(R.layout.progress,null);mProgress=(ProgressBar)v.findViewById(R.id.progress);builder.setView(v);builder.setNegativeButton("取消",newOnClickListener(){@OverridepublicvoidonClick(DialogInterfacedialog,intwhich){dialog.dismiss();interceptFlag=true;}});downloadDialog=builder.create();downloadDialog.show();downloadApk();}//启动下载线程开始
下载privatevoiddownloadApk(){downLoadThread=newThread(mdownApkRunnable);downLoadThread.start();
}privateRunnablemdownApkRunnable=newRunnable(){@Overridepublicvoidrun(){try{URLurl=newURL(apkUrl);HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.connect();intlength=conn.getContentLength();InputStreamis=conn.getInputStream();Filefile=newFile(savePath);if(!file.exists()){file.mkdir();}StringapkFile=saveFileName;FileApkFile=newFile(apkFile);FileOutputStreamfos=newFileOutputStream(ApkFile);intcount=0;bytebuf[]=newbyte[1024];do{intnumread=is.read(buf);count+=numread;progress=(int)(((float)count/length)*100);//更新进度mHandler.sendEmptyMessage(DOWN_UPDATE);if(numread<=0){//下载完成通知安装mHandler.sendEmptyMessage(DOWN_OVER);break;}fos.write(buf,0,numread);}while(!interceptFlag);//点击取消就停止
下载.fos.close();is.close();}catch(MalformedURLExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}};
//安装
下载好的软件privatevoidinstallApk(){Fileapkfile=newFile(saveFileName);if(!apkfile.exists()){return;}Intenti=newIntent(Intent.ACTION_VIEW);i.setDataAndType(Uri.parse("file://"+apkfile.toString()),"application/vnd.android.package-archive");mContext.startActivity(i);}