app版本更新,及安裝

思路:android

  1. 從服務器上拿到最新版本號,當前版本號。 比較版本號web

  2. 拿到下載地址,進行下載(後臺線程:例如 intentservice ,asyntask  , hanlder )服務器

  3. 進行安裝(   broadcastreciver上操做  )網絡

 

String newAppUrl=「」; //app下載連接app

private ProgressDialog progressdialog ;ide

 

 //比較版本,及發送更新信息
 public void compareVerson(){
         progressdialog=ProgressDialog.show(this,"版本信息", "正在檢查版本...");
         progressdialog.setCancelable(true);
         new Thread(new Runnable() {
                    @Override
                     public void run() {
                            int newVerson=getNewVerson(  );      / /獲取最新版本號,getNewVerson()沒有貼出
                            int currentVerson=getVersonCode();
                            Looper.prepare();
                            Message msg=handler.obtainMessage();
                             if(newVerson>=currentVerson+1){  //存在最新版本
                                   msg.arg1=2;
                             }
                             else{ //無最新版本
                                   msg.arg1=0;
                              }
                               handler.sendMessage(msg);
                              Looper.loop();
                     }
           }).start(); 
 }oop

 

//獲取版本號
 public int getVersonCode(){
            int versonCode;
            try {
                 PackageInfo packageInfo= getPackageManager().getPackageInfo(getPackageName(), 0);
                 versonCode= packageInfo.versionCode;
             } catch (Exception e) {
                   versonCode= 0 ;
                 e.printStackTrace();
              }
              return versonCode;
 }ui

 

private Handler handler = new Handler(new android.os.Handler.Callback() {
      public boolean handleMessage(Message msg) {

              switch (msg.arg1) {
                        case 0:  //對無最新版本的處理
                                    progressdialog.dismiss();
                                    Toast.makeText(LoginActivity.this,"暫無最新版本", Toast.LENGTH_SHORT).show();
                                     break;this

                        case 2:線程

                                 progressdialog.dismiss();

                                 new AlertDialog.Builder(LoginActivity.this)
                                 .setTitle("在WIFI下進行更新?")
                                 .setPositiveButton("肯定", new android.content.DialogInterface.OnClickListener() {
                                  @Override
                                      public void onClick(DialogInterface arg0, int arg1) {
      
                                        new MyAsynTask().execute(newAppUrl);
                                          arg0.dismiss();
                                   } })
                                  .setNegativeButton("取消", null)
                                  .create().show();

                                  break;

                       default:
                                   break;
                    }
                      if (progressdialog != null) {
                           if (progressdialog.isShowing()) {
                                    progressdialog.dismiss();
                             }
                         }
                    return false;
              }
 });

 

 

//在asytask中下載app
 public class MyAsynTask extends AsyncTask<String,Void,Boolean>{
         String weburi;
         //該方法在工做線程中被調用。在工做線程進行下載 操做
          protected Boolean doInBackground(String... arg0) {
                       weburi=arg0[0];
                 try {
                       downloadAPP(weburi);
                  } catch (Exception e) {
                        e.printStackTrace();
                        return false;
                 }
                      return  true ;
               }
                @Override
              protected void onPostExecute(Boolean result) {
                if(!result){
                   Toast.makeText(LoginActivity.this,"下載失敗", Toast.LENGTH_SHORT).show();
                    }
                 super.onPostExecute(result);
               }
 }

   public static long myDownloadReference;      //myDownloadReference變量是當前請求的id

    //下載app,記錄app所在路徑
   public void downloadAPP(String uri){
            try {
               DownloadManager manager=(DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
               Request request=new Request(Uri.parse(uri));
               request.setTitle("ndfixedassets.apk");  //文件下載時顯示的標題
               request.setNotificationVisibility(Request.VISIBILITY_VISIBLE); //下載完成後,notification會自動消失

               //運用在sdcard中專用文件

               request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,  "xxx.apk" );
               myDownloadReference=manager.enqueue(request);     //myDownloadReference變量是當前請求的id
 
 
              } catch (Exception e) {
                 e.printStackTrace();
           }
 }
 

 

public class InstallAppReciver extends BroadcastReceiver {
     //安裝下載好後的app
     public void onReceive( final Context context, Intent intent) {
            long reference =intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if(myDownloadReference==reference){     //接受到下載完最新該app後的操做
                     AlertDialog dialog= new AlertDialog.Builder(context)
                                        .setTitle("安裝新版本")
                                        .setMessage("覆蓋舊版本")
                                        .setPositiveButton("肯定",new android.content.DialogInterface.OnClickListener() {
                                             public void onClick(DialogInterface arg0, int arg1) {
                                                   install(context);
                                               } })
                                         .setNegativeButton("取消", null)
                                         .create();
                                       //設置dialog的類型確保,能在broadcastreceiver中正確彈出。
                                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                                          dialog.show();
                   }
         }
     public void install(Context context){
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                   Intent installintent =new Intent();
                  installintent.setAction(Intent.ACTION_VIEW);

                  //在Boradcast中啓動活動須要添加Intent.FLAG_ACTIVITY_NEW_TASK           

                  installintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


                 File file=new File(Environment.getExternalStoragePublicDirectory                 (Environment.DIRECTORY_DOWNLOADS), "xxx.apk");
                 installintent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
                 context.startActivity(installintent);


               }else{
                       Toast.makeText(context, "內存卡不存在或者不可用", Toast.LENGTH_SHORT).show();
               }
       }

}

 

 

 

 

//聯網前先檢查網絡狀況,在這裏,就不貼出來

 

 <receiver
            android:name="com.nandafixedassets.broadcastreceiver.InstallAppReciver">
            <intent-filter
                android:priority="100">
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
            </intent-filter>
 </receiver>


 

<!-- 系統級別的對話框的權限 -->
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>      

<!-- 鏈接網絡的權限 -->    <uses-permission android:name="android.permission.INTERNET" /><!-- 檢查網絡信息的權限 -->    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 在sdcard中寫入權限 -->    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>   

相關文章
相關標籤/搜索