现在的位置: 首页 > 综合 > 正文

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

2013年12月11日 ⁄ 综合 ⁄ 共 6150字 ⁄ 字号 评论关闭
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://skyoceanone.blog.51cto.com/3483859/677114

 

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.imageView1, 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(newURL("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();
    }
}
效果如下
 

 本文出自 “美丽的奇葩
博客,请务必保留此出处
http://skyoceanone.blog.51cto.com/3483859/677114

抱歉!评论已关闭.