欢迎来到天天文库
浏览记录
ID:37724637
大小:248.50 KB
页数:7页
时间:2019-05-29
《分享为程序添加版本自动更新功能(转+详细分析)》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、可达0OverView:程序通过后台每天检查是否有最新版本,如果需要更新当前版本,将弹出对话框让用户选择是否在当前通过Market来更新软件。KnowledgePoints:·SharedPreferences:一个轻量级的存储方法,类似于经常使用的.ini文件,它也是通过检索关键字来取得相应的数值。之所以是成为轻量级,是因为它所能应用的数值类型有限,对于存储较大数值,效率相对较低。官方参考·System.currentTimeMillis:将当前时间以毫秒作为单位来表示,用于比较两个时间的先后顺序。(其数值表示从1970-01-0100:00:00直到
2、当前时间的总毫秒数)官方参考·通过网络来读取信息:在checkUpdate()方法中包含了通过制定的URL来读取网络资源。具体操作步骤,请参考源代码。·Runnable:在其内部的Run()方法中实现所要执行的任何代码,当这个runnableinterface被调用后可以视作为新的线程。SourceCode:1.publicclasshelloextendsActivity {2. /**Calledwhentheactivityisfirstcreated.*/3. privateHandlermHandler;4. 5
3、. @Override6. publicvoidonCreate(BundlesavedInstanceState){7. super.onCreate(savedInstanceState);8. setContentView(R.layout.main);9. 10. mHandler=newHandler();11.12. /*GetLastUpdateTimefromPreferences*/13. SharedPreferencesprefs=getPreferences(0);1
4、4. longlastUpdateTime= prefs.getLong("lastUpdateTime",System.currentTimeMillis());15.16. intcurVersion=0;17. try{18. curVersion=getPackageManager().getPackageInfo("linhai.com.hello",0).versionCode;19. }catch(NameNotFoundExceptione){20.
5、 //TODOAuto-generatedcatchblock21. e.printStackTrace();22. }23. Log.i("DEMO",String.valueOf(curVersion));24. /*ShouldActivityCheckforUpdatesNow?*/ksksk可达01. if((lastUpdateTime+(24*60*60*1000))6、 /*SavecurrenttimestampfornextCheck*/4. lastUpdateTime=System.currentTimeMillis();5. SharedPreferences.Editoreditor=getPreferences(0).edit();6. editor.putLong("lastUpdateTime",lastUpdateTime);7. editor.commit(); 8.9. /*StartUpdate*/10. 7、 // checkUpdate.start();11. }12. }13.14. /*ThisThreadchecksforUpdatesintheBackground*/15. privateThreadcheckUpdate=newThread()16. {17. publicvoidrun(){18. try{19. URLupdateURL=newURL("http://my.company.com/update");20. URLConnectionconn=8、updateURL.openConnection();21.
6、 /*SavecurrenttimestampfornextCheck*/4. lastUpdateTime=System.currentTimeMillis();5. SharedPreferences.Editoreditor=getPreferences(0).edit();6. editor.putLong("lastUpdateTime",lastUpdateTime);7. editor.commit(); 8.9. /*StartUpdate*/10.
7、 // checkUpdate.start();11. }12. }13.14. /*ThisThreadchecksforUpdatesintheBackground*/15. privateThreadcheckUpdate=newThread()16. {17. publicvoidrun(){18. try{19. URLupdateURL=newURL("http://my.company.com/update");20. URLConnectionconn=
8、updateURL.openConnection();21.
此文档下载收益归作者所有