Android联网更新应用
程序员文章站
2022-11-14 09:31:04
UpdateInfo WelcomeActivity: ......
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 @Override 163 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 * @return 189 */ 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 @Override 217 public void onSuccess(String content) { 218 //解析json数据 219 updateInfo = JSON.parseObject(content, UpdateInfo.class); 220 handler.sendEmptyMessage(DOWNLOAD_VERSION_SUCCESS); 221 } 222 223 @Override 224 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 // @Override 253 // public void onAnimationStart(Animation animation) { 254 // 255 // } 256 // //当动画结束时:调用如下方法 257 // @Override 258 // public void onAnimationEnd(Animation animation) { 259 // Intent intent = new Intent(WelcomeActivity.this,MainActivity.class); 260 // startActivity(intent); 261 // finish();//销毁当前页面 262 // } 263 // 264 // @Override 265 // public void onAnimationRepeat(Animation animation) { 266 // 267 // } 268 // }); 269 //方式二:使用handler 270 // handler.postDelayed(new Runnable() { 271 // @Override 272 // 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 }
上一篇: 云计算:IT人还没准备好!
下一篇: 大数据让互联网广告投放更精准