Android App自动更新之通知栏下载
本文实例为大家分享了AndroidApp自动更新通知栏下载的具体代码,供大家参考,具体内容如下
版本更新说明
这里有调用UpdateService启动服务检查下载安装包等
1.文件下载,下完后写入到sdcard
2.如何在通知栏上显示下载进度
3.下载完毕自动安装
4.如何判断是否有新版本
版本更新的主类
packagecom.wei.update; importjava.io.IOException; importjava.io.InputStream; importjava.net.URL; importjava.util.HashMap; importjavax.xml.parsers.DocumentBuilder; importjavax.xml.parsers.DocumentBuilderFactory; importorg.json.JSONException; importorg.json.JSONObject; importorg.w3c.dom.Document; importorg.w3c.dom.Element; importorg.w3c.dom.Node; importorg.w3c.dom.NodeList; importorg.xmlpull.v1.XmlPullParser; importorg.xmlpull.v1.XmlPullParserException; importorg.xmlpull.v1.XmlPullParserFactory; importcom.wei.util.MyApplication; importandroid.app.AlertDialog; importandroid.content.Context; importandroid.content.DialogInterface; importandroid.content.Intent; importandroid.content.pm.PackageManager.NameNotFoundException; importandroid.os.Handler; /** *版本更新主类,这里有调用UpdateService启动服务检查下载安装包等1.文件下载,下完后写入到sdcard2.如何在通知栏上显示下载进度 *3.下载完毕自动安装4.如何判断是否有新版本 * *@authordavid */ publicclassUpdateManager{ privatestaticStringpackageName;//="com.yipinzhe";//应用的包名 privatestaticStringjsonUrl="version.txt";//JSON版本文件URL privatestaticStringxmlUrl="version.xml";//XML版本文件URL privatestaticfinalStringDOWNLOAD_DIR="/";//应用下载后保存的子目录 privateContextmContext; HashMapmHashMap;//保存解析的XML信息 intversionCode,isNew; publicUpdateManager(Contextcontext){ this.mContext=context; packageName=context.getPackageName(); jsonUrl=MyApplication.site+jsonUrl; xmlUrl=MyApplication.site+xmlUrl; checkVersion(); } HandlercheckHandler=newHandler(){ @Override publicvoidhandleMessage(android.os.Messagemsg){ if(msg.what==1){ //发现新版本,提示用户更新 StringBuffermessage=newStringBuffer(); message.append(mHashMap.get("note").replace("|","\n")); AlertDialog.Builderalert=newAlertDialog.Builder(mContext); alert.setTitle("软件升级") .setMessage(message.toString()) .setPositiveButton("更新", newDialogInterface.OnClickListener(){ @Override publicvoidonClick(DialogInterfacedialog, intwhich){ //开启更新服务UpdateService System.out.println("你点击了更新"); IntentupdateIntent=newIntent( mContext,UpdateService.class); /** *updateIntent.putExtra("downloadDir", *DOWNLOAD_DIR); *updateIntent.putExtra("apkUrl", *mHashMap.get("url")); */ mContext.startService(updateIntent); } }) .setNegativeButton("取消", newDialogInterface.OnClickListener(){ @Override publicvoidonClick(DialogInterfacedialog, intwhich){ dialog.dismiss(); } }); alert.create().show(); } }; }; /** *检查是否有新版本 */ publicvoidcheckVersion(){ try{ //获取软件版本号,对应AndroidManifest.xml下android:versionCode versionCode=mContext.getPackageManager().getPackageInfo( packageName,0).versionCode; }catch(NameNotFoundExceptione){ e.printStackTrace(); } newThread(){ @Override publicvoidrun(){ Stringresult=null; /** *try{//如果服务器端是JSON文本文件result= *MyApplication.handleGet(jsonUrl);if(result!=null){ *mHashMap=parseJSON(result);}}catch(Exceptione1){ *e1.printStackTrace();} */ InputStreaminStream=null; try{ //本机XML文件 inStream=UpdateManager.class.getClassLoader().getResourceAsStream("version.xml"); //如果服务器端是XML文件 inStream=newURL(xmlUrl).openConnection().getInputStream(); if(inStream!=null) mHashMap=parseXml(inStream); }catch(Exceptione1){ e1.printStackTrace(); } if(mHashMap!=null){ intserviceCode=Integer.valueOf(mHashMap.get("version")); if(serviceCode>versionCode){//版本判断,返回true则有新版本 isNew=1; } } checkHandler.sendEmptyMessage(isNew); }; }.start(); } /** *解析服务器端的JSON版本文件 */ publicHashMap parseJSON(Stringstr){ HashMap hashMap=newHashMap (); try{ JSONObjectobj=newJSONObject(str); hashMap.put("version",obj.getString("version")); hashMap.put("name",obj.getString("name")); hashMap.put("url",obj.getString("url")); hashMap.put("note",obj.getString("note")); }catch(JSONExceptione){ e.printStackTrace(); } returnhashMap; } /** *解析服务器端的XML版本文件 */ publicHashMap parseXml(InputStreaminputStream){ HashMap hashMap=newHashMap (); try{ XmlPullParserparser=XmlPullParserFactory.newInstance().newPullParser(); parser.setInput(inputStream,"GBK");//设置数据源编码 inteventCode=parser.getEventType();//获取事件类型 while(eventCode!=XmlPullParser.END_DOCUMENT){ System.out.println("循环开始"); switch(eventCode){ caseXmlPullParser.START_DOCUMENT://开始读取XML文档 System.out.println("START_DOCUMENT"); break; caseXmlPullParser.START_TAG://开始读取某个标签 if("version".equals(parser.getName())){ hashMap.put(parser.getName(),parser.nextText()); }elseif("name".equals(parser.getName())){ hashMap.put(parser.getName(),parser.nextText()); }elseif("url".equals(parser.getName())){ hashMap.put(parser.getName(),parser.nextText()); }elseif("note".equals(parser.getName())){ hashMap.put(parser.getName(),parser.nextText()); } break; caseXmlPullParser.END_TAG: break; } eventCode=parser.next();//继续读取下一个元素节点,并获取事件码 } System.out.println(hashMap.get("version")); }catch(Exceptione){ } returnhashMap; /** *try{ DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance(); DocumentBuilderbuilder=factory.newDocumentBuilder(); Documentdocument=builder.parse(inStream); Elementroot=document.getDocumentElement();//获取根节点 NodeListchildNodes=root.getChildNodes();//获得所有子节点,然后遍历 for(intj=0;j 版本更新的服务类
packagecom.wei.update; importjava.io.File; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.net.HttpURLConnection; importjava.net.URL; importcom.wei.util.MyApplication; importcom.wei.wotao.R; //importandroid.annotation.SuppressLint; importandroid.app.Notification; importandroid.app.NotificationManager; importandroid.app.PendingIntent; importandroid.app.Service; importandroid.content.Intent; importandroid.net.Uri; importandroid.os.Environment; importandroid.os.Handler; importandroid.os.IBinder; importandroid.os.Message; importandroid.view.View; importandroid.widget.RemoteViews; /** *下载安装包的服务类 *@authordavid */ publicclassUpdateServiceextendsService{ //文件存储 privateFilesaveDir; privateFilesaveFile; privateStringapkUrl; //通知栏 privateNotificationManagerupdateNotificationManager=null; privateNotificationupdateNotification=null; //通知栏跳转Intent privateIntentupdateIntent=null; privatePendingIntentupdatePendingIntent=null; //下载状态 privatefinalstaticintDOWNLOAD_COMPLETE=0; privatefinalstaticintDOWNLOAD_FAIL=1; privateRemoteViewscontentView; @Override publicintonStartCommand(Intentintent,intflags,intstartId){ System.out.println("onStartCommand"); contentView=newRemoteViews(getPackageName(),R.layout.activity_app_update); //获取传值 StringdownloadDir=intent.getStringExtra("downloadDir"); apkUrl=MyApplication.site+intent.getStringExtra("apkUrl"); //如果有SD卡,则创建APK文件 if(android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment .getExternalStorageState())){ saveDir=newFile(Environment.getExternalStorageDirectory(), downloadDir); saveFile=newFile(saveDir.getPath(),getResources() .getString(R.string.app_name)+".apk"); } this.updateNotificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); this.updateNotification=newNotification(); //设置下载过程中,点击通知栏,回到主界面 updateIntent=newIntent(); updatePendingIntent=PendingIntent.getActivity(this,0,updateIntent,0); //设置通知栏显示内容 updateNotification.icon=R.drawable.icon_info; updateNotification.tickerText="开始下载"; updateNotification.contentView.setProgressBar(R.id.progressBar1,100,0,true); updateNotification.setLatestEventInfo(this, getResources().getString(R.string.app_name),"0%", updatePendingIntent); //发出通知 updateNotificationManager.notify(0,updateNotification); newThread(newDownloadThread()).start(); returnsuper.onStartCommand(intent,flags,startId); } @Override publicIBinderonBind(Intentintent){ returnnull; } /** *下载的线程 */ privateclassDownloadThreadimplementsRunnable{ Messagemessage=updateHandler.obtainMessage(); publicvoidrun(){ message.what=DOWNLOAD_COMPLETE; if(saveDir!=null&&!saveDir.exists()){ saveDir.mkdirs(); } if(saveFile!=null&&!saveFile.exists()){ try{ saveFile.createNewFile(); }catch(IOExceptione){ e.printStackTrace(); } } try{ longdownloadSize=downloadFile(apkUrl,saveFile); if(downloadSize>0){//下载成功 updateHandler.sendMessage(message); } }catch(Exceptionex){ ex.printStackTrace(); message.what=DOWNLOAD_FAIL; updateHandler.sendMessage(message);//下载失败 } } publiclongdownloadFile(StringdownloadUrl,FilesaveFile) throwsException{ intdownloadCount=0; intcurrentSize=0; longtotalSize=0; intupdateTotalSize=0; intrate=0;//下载完成比例 HttpURLConnectionhttpConnection=null; InputStreamis=null; FileOutputStreamfos=null; try{ URLurl=newURL(downloadUrl); httpConnection=(HttpURLConnection)url.openConnection(); httpConnection.setRequestProperty("User-Agent", "PacificHttpClient"); if(currentSize>0){ httpConnection.setRequestProperty("RANGE","bytes=" +currentSize+"-"); } httpConnection.setConnectTimeout(200000); httpConnection.setReadTimeout(200000); updateTotalSize=httpConnection.getContentLength();//获取文件大小 if(httpConnection.getResponseCode()==404){ thrownewException("fail!"); } is=httpConnection.getInputStream(); fos=newFileOutputStream(saveFile,false); bytebuffer[]=newbyte[1024*1024*3]; intreadsize=0; while((readsize=is.read(buffer))!=-1){ fos.write(buffer,0,readsize); totalSize+=readsize;//已经下载的字节数 rate=(int)(totalSize*100/updateTotalSize);//当前下载进度 //为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次 if((downloadCount==0)||rate-0>downloadCount){ downloadCount+=1; updateNotification.setLatestEventInfo( UpdateService.this,"正在下载",rate+"%", updatePendingIntent);//设置通知的内容、标题等 updateNotification.contentView.setProgressBar(R.id.progressBar1,100,rate,true); updateNotificationManager.notify(0,updateNotification);//把通知发布出去 } } }finally{ if(httpConnection!=null){ httpConnection.disconnect(); } if(is!=null){ is.close(); } if(fos!=null){ fos.close(); } } returntotalSize; } } privateHandlerupdateHandler=newHandler(){ @Override publicvoidhandleMessage(Messagemsg){ switch(msg.what){ caseDOWNLOAD_COMPLETE: //当下载完毕,自动安装APK(ps,打电话发短信的启动界面工作) Uriuri=Uri.fromFile(saveFile);//根据File获得安装包的资源定位符 IntentinstallIntent=newIntent(Intent.ACTION_VIEW);//设置Action installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//新的Activity会在一个新任务打开,而不是在原先的任务栈 installIntent.setDataAndType(uri,"application/vnd.android.package-archive");//设置URI的数据类型 startActivity(installIntent);//把打包的Intent传递给startActivity //当下载完毕,更新通知栏,且当点击通知栏时,安装APK updatePendingIntent=PendingIntent.getActivity(UpdateService.this,0,installIntent,0); updateNotification.defaults=Notification.DEFAULT_SOUND;//铃声提醒 updateNotification.setLatestEventInfo(UpdateService.this,getResources().getString(R.string.app_name), "下载完成,点击安装",updatePendingIntent); updateNotificationManager.notify(0,updateNotification); //停止服务 stopService(updateIntent); break; caseDOWNLOAD_FAIL: //下载失败 updateNotification.setLatestEventInfo(UpdateService.this, getResources().getString(R.string.app_name), "下载失败,网络连接超时",updatePendingIntent); updateNotificationManager.notify(0,updateNotification); break; default: stopService(updateIntent); break; } } }; }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。