Android聯網更新應用

来源:https://www.cnblogs.com/ganchuanpu/archive/2018/05/08/9006820.html
-Advertisement-
Play Games

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 }

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • MariaDB/MySQL備份恢復系列: 備份和恢復(一):mysqldump工具用法詳述 備份和恢復(二):導入、導出表數據 備份和恢復(三):xtrabackup用法和原理詳述 本文目錄: 1.安裝xtrabackup 2.備份鎖 3.xtrabackup備份原理說明 3.1 備份過程(back ...
  • MySQL元數據 Meta Data,一般是結構化數據(如存儲在資料庫里的數據,欄位長度、類型、預設值等等)。Meta Data就是描述數據的數據,在MySQL中描述有哪些資料庫、哪些表、表有多少欄位、類型。 MySQL元數據信息 查詢結果信息,SELECT、UPDATE或DELETE語句影響的行數 ...
  • 當實際項目上線到生產環境中,難以避免一些意外情況,如數據丟失、伺服器停機等。對於系統的搜索服務來說,當遇到停機的情況意味著在停機這段時間內,用戶都不能通過搜索的相關功能進行訪問數據,停機意味著將這一段時間內的數據服務完全停止。如果項目是互聯網項目依賴於用戶數量,這將嚴重影響用戶訪問和用戶的產品體驗。 ...
  • 本文主要總結並記錄一下簡單且常用的mysql 在cmd 視窗中操作的基本命令 命令停止mysql 資料庫服務 1.(cmd)命令行 2.手動: 1. 使用快捷鍵 ctr+alt+delete =》2. 啟動任務管理器=》3. 進入服務 =》4.找到mysql 將其啟動/關閉 3.登錄/退出mysql ...
  • 設計模式六大基本原則 1.單一職責原則 英文:Single Responsibility Principles,縮寫SRP 定義:就一個類而言,應該僅有一個引起它變化的原因。 理解:例如兩個完全不一樣的功能就不應該放在一個類中。一個類總應該是一組相關性很高的函數,數據的封裝。 對應一個類,不求功能面 ...
  • 最近用到JS和OC原生方法調用的問題,查了許多資料都語焉不詳,自己記錄一下吧,如果有誤歡迎聯繫我指出。 JS中調用OC方法有三種方式: 先上OC代碼 // 設置javaScriptContext上下文 self.jsContext = [self.webView valueForKeyPath:@" ...
  • 最近項目測試出一個隱藏已久的bug,經過多番測試,發現在iOS9下自定義的一個UICollectionViewCell只走一次awakeFromNib。 具體情況是,項目中有一個控制器用到了自定義的UICollectionView,有四組數據,然而有三組自定義的UICollectionViewCel ...
  • as clean項目之後有時候會報錯。 可以找得到目錄刪掉,然後重啟as,但是下次clean可能又會報類似的錯誤。 解決方法如下: 進入File-Setting-Build,Execution,Deployment-Instant Run 取消勾選 Restart activity on code ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...