Android源码之联网更新应用
白羽 2018-07-02 来源 :网络 阅读 690 评论 0

摘要:本文将带你了解Android源码之联网更新应用,希望本文对大家学Android有所帮助。


 

 

 

 

UpdateInfo

 

public class UpdateInfo {

    public String version;//服务器的最新版本值

    public String apkUrl;//最新版本的路径

    public String desc;//版本更新细节

}

 

WelcomeActivity:

 

  1 public class WelcomeActivity extends Activity {  2   3     private static final int TO_MAIN = 1;  4     private static final int DOWNLOAD_VERSION_SUCCESS = 2;  5     private static final int DOWNLOAD_APK_FAIL = 3;  6     private static final int DOWNLOAD_APK_SUCCESS = 4;  7     @Bind(R.id.iv_welcome_icon)  8     ImageView ivWelcomeIcon;  9     @Bind(R.id.rl_welcome) 10     RelativeLayout rlWelcome; 11     @Bind(R.id.tv_welcome_version) 12     TextView tvWelcomeVersion; 13     private boolean connect; 14     private long startTime; 15  16     private Handler handler = new Handler() { 17         @Override 18         public void handleMessage(Message msg) { 19             switch (msg.what) { 20                 case TO_MAIN: 21                     finish(); 22                     startActivity(new Intent(WelcomeActivity.this, MainActivity.class)); 23                     break; 24                 case DOWNLOAD_VERSION_SUCCESS: 25                     //获取当前应用的版本信息 26                     String version = getVersion(); 27                     //更新页面显示的版本信息 28                     tvWelcomeVersion.setText(version); 29                     //比较服务器获取的最新的版本跟本应用的版本是否一致 30                     if(version.equals(updateInfo.version)){ 31                         UIUtils.toast("当前应用已经是最新版本",false); 32                         toMain(); 33                     }else{ 34                         new AlertDialog.Builder(WelcomeActivity.this) 35                                     .setTitle("下载最新版本") 36                                     .setMessage(updateInfo.desc) 37                                     .setPositiveButton("确定", new DialogInterface.OnClickListener() { 38                                         @Override 39                                         public void onClick(DialogInterface dialog, int which) { 40                                             //下载服务器保存的应用数据 41                                             downloadApk(); 42                                         } 43                                     }) 44                                     .setNegativeButton("取消", new DialogInterface.OnClickListener() { 45                                         @Override 46                                         public void onClick(DialogInterface dialog, int which) { 47                                             toMain(); 48                                         } 49                                     }) 50                                     .show(); 51                     } 52  53                     break; 54                 case DOWNLOAD_APK_FAIL: 55                     UIUtils.toast("联网下载数据失败",false); 56                     toMain(); 57                     break; 58                 case DOWNLOAD_APK_SUCCESS: 59                     UIUtils.toast("下载应用数据成功",false); 60                     dialog.dismiss(); 61                     installApk();//安装下载好的应用 62                     finish();//结束当前的welcomeActivity的显示 63                     break; 64             } 65  66         } 67     }; 68  69     private void installApk() { 70         Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE"); 71         intent.setData(Uri.parse("file:" + apkFile.getAbsolutePath())); 72         startActivity(intent); 73     } 74  75     private ProgressDialog dialog; 76     private File apkFile; 77     private void downloadApk() { 78         //初始化水平进度条的dialog 79         dialog = new ProgressDialog(this); 80         dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 81         dialog.setCancelable(false); 82         dialog.show(); 83         //初始化数据要保持的位置 84         File filesDir; 85         if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ 86             filesDir = this.getExternalFilesDir(""); 87         }else{ 88             filesDir = this.getFilesDir(); 89         } 90         apkFile = new File(filesDir,"update.apk"); 91  92         //启动一个分线程联网下载数据: 93         new Thread(){ 94             public void run(){ 95                 String path = updateInfo.apkUrl; 96                 InputStream is = null; 97                 FileOutputStream fos = null; 98                 HttpURLConnection conn = null; 99                 try {100                     URL url = new URL(path);101                     conn = (HttpURLConnection) url.openConnection();102 103                     conn.setRequestMethod("GET");104                     conn.setConnectTimeout(5000);105                     conn.setReadTimeout(5000);106 107                     conn.connect();108 109                     if(conn.getResponseCode() == 200){110                         dialog.setMax(conn.getContentLength());//设置dialog的最大值111                         is = conn.getInputStream();112                         fos = new FileOutputStream(apkFile);113 114                         byte[] buffer = new byte[1024];115                         int len;116                         while((len = is.read(buffer)) != -1){117                             //更新dialog的进度118                             dialog.incrementProgressBy(len);119                             fos.write(buffer,0,len);120 121                             SystemClock.sleep(1);122                         }123 124                         handler.sendEmptyMessage(DOWNLOAD_APK_SUCCESS);125 126                     }else{127                         handler.sendEmptyMessage(DOWNLOAD_APK_FAIL);128 129                     }130 131                 } catch (Exception e) {132                     e.printStackTrace();133                 }finally{134                     if(conn != null){135                         conn.disconnect();136                     }137                     if(is != null){138                         try {139                             is.close();140                         } catch (IOException e) {141                             e.printStackTrace();142                         }143                     }144                     if(fos != null){145                         try {146                             fos.close();147                         } catch (IOException e) {148                             e.printStackTrace();149                         }150                     }151                 }152 153 154             }155         }.start();156 157 158     }159 160     private UpdateInfo updateInfo;161 162     @Override163     protected void onCreate(Bundle savedInstanceState) {164         super.onCreate(savedInstanceState);165 166         // 去掉窗口标题167         requestWindowFeature(Window.FEATURE_NO_TITLE);168         // 隐藏顶部的状态栏169         getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);170 171         setContentView(R.layout.activity_welcome);172         ButterKnife.bind(this);173 174 175         //将当前的activity添加到ActivityManager中176         ActivityManager.getInstance().add(this);177         //提供启动动画178         setAnimation();179 180         //联网更新应用181         updateApkFile();182 183     }184 185     /**186      * 当前版本号187      *188      * @return189      */190     private String getVersion() {191         String version = "未知版本";192         PackageManager manager = getPackageManager();193         try {194             PackageInfo packageInfo = manager.getPackageInfo(getPackageName(), 0);195             version = packageInfo.versionName;196         } catch (PackageManager.NameNotFoundException e) {197             //e.printStackTrace(); //如果找不到对应的应用包信息, 就返回"未知版本"198         }199         return version;200     }201 202     private void updateApkFile() {203         //获取系统当前时间204         startTime = System.currentTimeMillis();205 206         //1.判断手机是否可以联网207         boolean connect = isConnect();208         if (!connect) {//没有移动网络209             UIUtils.toast("当前没有移动数据网络", false);210             toMain();211         } else {//有移动网络212             //联网获取服务器的最新版本数据213             AsyncHttpClient client = new AsyncHttpClient();214             String url = AppNetConfig.UPDATE;215             client.post(url, new AsyncHttpResponseHandler() {216                 @Override217                 public void onSuccess(String content) {218                     //解析json数据219                     updateInfo = JSON.parseObject(content, UpdateInfo.class);220                     handler.sendEmptyMessage(DOWNLOAD_VERSION_SUCCESS);221                 }222 223                 @Override224                 public void onFailure(Throwable error, String content) {225                     UIUtils.toast("联网请求数据失败", false);226                     toMain();227                 }228             });229 230         }231     }232 233     private void toMain() {234         long currentTime = System.currentTimeMillis();235         long delayTime = 3000 - (currentTime - startTime);236         if (delayTime < 0) {237             delayTime = 0;238         }239 240 241         handler.sendEmptyMessageDelayed(TO_MAIN, delayTime);242     }243 244 245     private void setAnimation() {246         AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);//0:完全透明  1:完全不透明247         alphaAnimation.setDuration(3000);248         alphaAnimation.setInterpolator(new AccelerateInterpolator());//设置动画的变化率249 250         //方式一:251 //        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {252 //            @Override253 //            public void onAnimationStart(Animation animation) {254 //255 //            }256 //            //当动画结束时:调用如下方法257 //            @Override258 //            public void onAnimationEnd(Animation animation) {259 //                Intent intent = new Intent(WelcomeActivity.this,MainActivity.class);260 //                startActivity(intent);261 //                finish();//销毁当前页面262 //            }263 //264 //            @Override265 //            public void onAnimationRepeat(Animation animation) {266 //267 //            }268 //        });269         //方式二:使用handler270 //        handler.postDelayed(new Runnable() {271 //            @Override272 //            public void run() {273 //                Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);274 //                startActivity(intent);275 ////                finish();//销毁当前页面276 //                //结束activity的显示,并从栈空间中移除277 //                ActivityManager.getInstance().remove(WelcomeActivity.this);278 //            }279 //        }, 3000);280 281         //启动动画282         rlWelcome.startAnimation(alphaAnimation);283 284     }285 286     public boolean isConnect() {287         boolean connected = false;288 289         ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);290         NetworkInfo networkInfo = manager.getActiveNetworkInfo();291         if (networkInfo != null) {292             connected = networkInfo.isConnected();293         }294         return connected;295     }296 }

 

 


本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!


本文由 @白羽 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程