Android如何更新app的版本(中級)

 

Android如何更新app的版本(中級)
 
 
版本更新
看看我們要用到哪些技術   1 自定義通知欄
                                           2 HTTP 下載
                                           3 AsyncTask
                                           4 刷新通知欄中的進度條
                                           5 執行 apk安裝的隱士意圖
                                           6 Toast
                                           7簽名(安裝時系統會自動檢測簽名是否一致)
                                           8獲得服務端和客戶端的版本號
上代碼
(1)點擊事件判斷是否有新版本更新 (2)自定義一個通知 同時刷新下載進度
              (3) 異步下載新版本app      (4) 隱士意圖來安裝
 
首先別忘了寫權限!!!!!超愛忘得東西 恨死它了
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INSTALL_PACKAGES"></uses-permission>
 
       private Runnable mrun;
    private NotificationManager mNotificationManager;
    private Notification notification;
    private RemoteViews remoteviews;
    private int count;
    private int loadversion;
    private int version;
 
 
    //升級按鈕點擊事件的方法 通過服務器來解析JSON 得到版本號 判斷是否來通知下載
    private void upgrade() {
       
        PackageManager nPackageManager=getPackageManager();//得到包管理器
        try {
            PackageInfo nPackageInfo=nPackageManager
                    .getPackageInfo(getPackageName(),PackageManager.GET_CONFIGURATIONS );
            loadversion=nPackageInfo.versionCode;//得到現在app的版本號
           
        } catch (NameNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //服務器端通過GET 得到JSON
        String json=JSandBitmap.httpGetDemo("http://192.168.14.234/version.json");
        try {
            JSONArray jsonArray=new JSONArray(json);
            JSONObject jsonObject=jsonArray.getJSONObject(0);
             version = jsonObject.getInt("version");//得到服務端的app版本號
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if((loadversion<version)){//如果有新版本發送通知開始下載
           
            sendNotification();
        }else{                 //如果沒有 彈出對話框告知用戶
            new AlertDialog.Builder(this)
            .setTitle("update cancel")
            .setMessage("Sorry Not new Version ")
            .setNegativeButton("cencel", null).show();
        }
    }
 
 
    //此方法來發送下載通知 採用的是自定義通知欄 並且更加下載的進度來刷新進度條
    //自定義通知的方法 在上上篇的博文中 這裏不做太多的解釋
    private void sendNotification() {
       
         mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
         notification = new Notification(
                R.drawable.player_play_light, "Midiplay",
                System.currentTimeMillis());
       
        remoteviews= new RemoteViews("com.tarena.gsd110623.midiplayonline", R.layout.mynotiifcation);
        remoteviews.setImageViewResource(R.id.p_w_picpathView1, R.drawable.a00);
        notification.contentView=remoteviews;
       
        Intent intent=new Intent(this,install.class);//PendingIntent 調用的系統的安裝隱士意圖 後面紅色的代碼
        PendingIntent pendingintent=PendingIntent.getActivity(this, 0, intent, 0);
        notification.contentIntent=pendingintent;
        mrun=new Runnable() {//這個Runnable 用來根據下載進度來刷新進度條
           
            @Override
            public void run() {
                if(count<98){//紫色的count 是異步下載計算出來設置進度的值
                    remoteviews.setProgressBar(R.id.progressBar1, 100, count, false);
                    remoteviews.setTextViewText(R.id.textView1, count+"%");
                   
                    mNotificationManager.notify(8888, notification);
                    handler.postDelayed(mrun, 300);
                }else{//這裏計算出來的count 不是那麼準確 所以下載完成後 給一個固定值做爲下載完成
                    remoteviews.setProgressBar(R.id.progressBar1, 100, 100, false);
                    remoteviews.setTextViewText(R.id.textView1, 100+"%");
                   
                    mNotificationManager.notify(8888, notification);
                    Toast.makeText(Welcome.this, "download over", Toast.LENGTH_SHORT);//提示用戶下載成功
                }
                }
            };
        handler.postDelayed(mrun, 300);
        Update_AsyncTask mUpdate_AsyncTask=new Update_AsyncTask();
        try {//啓動下載
            mUpdate_AsyncTask.execute(new URL("http://192.168.14.234/android_project_midiplayonline.apk"));
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
 
    //這個內部類用來異步下載新版本app 通過服務端下載這裏不多說了
     class Update_AsyncTask extends AsyncTask<URL, Integer, Object>{
        @Override
        protected Object doInBackground(URL... params) {
            // TODO Auto-generated method stub
            try {
                URLConnection con = params[0].openConnection();
               
                if (HttpURLConnection.HTTP_OK != ((HttpURLConnection)con).getResponseCode())
                {
                    Log.i("Main", "connection failed");
                   return null;
                }
                InputStream is = con.getInputStream();
                int contentlength=con.getContentLength();//得到下載的總長度
                System.out.println(contentlength);
                File file=new File(Constant.APK_FILE_PATH);
                if(!file.exists()){
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }
                FileOutputStream out=new FileOutputStream(file);
                int current = 0;
                int x=0;
                byte[]arr=new byte[1024];
                while ( (current = is.read(arr)) != -1 ){
                    out.write(arr, 0, current);
                    x=x+current;
                    count=(int)(100*x/contentlength);//計算下載的百分百
                }
                is.close();
            } catch (Exception e) {
            }return null;
        }
     }
 
/*
 * 此類爲系統安裝的隱士意圖
 */
public class install extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Intent notify_Intent = new Intent(Intent.ACTION_VIEW);
        notify_Intent.setDataAndType(Uri.fromFile(new File(Constant.APK_FILE_PATH)), "application/vnd.android.package-archive");
        startActivity(notify_Intent);
        //取消上一個通知
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.cancel(8888);
        overridePendingTransition(0, 0);
        finish();
    }
}
效果如下
 

 
   
 
 
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章