Android聯網更新應用

 

 

UpdateInfoandroid

public class UpdateInfo { public String version;//服務器的最新版本值
    public String apkUrl;//最新版本的路徑
    public String desc;//版本更新細節
}

WelcomeActivity:json

 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 }
相關文章
相關標籤/搜索