Android版本更新使用DownloadManager



public class MainActivity extends Activity implements OnClickListener,VersionManager.OnUpdateListener{
private Button button;
private SharedPreferences prefs;
    private  String DL_ID = "update_app_id";
    private DownloadManager downloadManager;
    private VersionManager manager;
    
    
    private Handler handler = new Handler() {//用handler处理异步请求后得到的下载链接地址
        public void handleMessage(Message msg) {


            switch (msg.what) {
                case 021:
                    String downloadURL = (String) msg.obj;
                    Log.d("aa", "downloadURL==" + downloadURL);
                    if (downloadURL != null) {
                        if (downloadURL.equals("http://222.73.3.43/sqdd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk?mkey=5523a9bb6eb200cf&f=188a&p=.apk")) {
                        VersionManager.AppVersion version = new VersionManager.AppVersion();
                            // 设置文件url
                            version.setApkUrl(downloadURL);
                            // 设置文件名
                            version.setFileName("QQ");
                            // 设置文件在sd卡的目录
                            version.setFilePath("update");
                            // 设置app当前版本号
                            version.setVersionCode(getVersionCode(MainActivity.this));//旧版本号


                            manager = VersionManager.getInstance(MainActivity.this, version);
                            manager.setOnUpdateListener(MainActivity.this);//监听
                            manager.checkUpdateInfo();


                        } else {
                            Toast.makeText(MainActivity.this, "已经是最新版本", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;


                default:
                    break;
            }
            super.handleMessage(msg);
        }


    };
    


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)this.findViewById(R.id.button);
button.setOnClickListener(this);
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);



}


@Override
public void onClick(View arg0) {
int id=arg0.getId();
if(id==R.id.button){
    int versionCode =getVersionCode(this);//旧版本号
           Log.d("aa", "versionCode==" + versionCode);
           int status=querydown();//查询下载状态
           if(status==DownloadManager.STATUS_RUNNING){
            this.onDownloading();
           }else if(status==DownloadManager.STATUS_PAUSED){
               Toast.makeText(MainActivity.this, "暂停下载中", Toast.LENGTH_SHORT).show();
           }
           else{
               new CheckUpdate(handler, this, versionCode).execute();//请求后台服务器,得到新版本号
           }
}

}
    public int querydown(){
        DownloadManager.Query query = new DownloadManager.Query();
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        query.setFilterById(prefs.getLong(DL_ID, 0));
        Log.d("status","downloadManagerId="+Long.toString(prefs.getLong(DL_ID, 0)));
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c
                    .getColumnIndex(DownloadManager.COLUMN_STATUS));
            return status;
        }
        return 0;
    }


    @Override
    public void onSuccess() {
        Log.d("aa", "onSuccess()");
        Toast.makeText(MainActivity.this, "下载成功等待安装", Toast.LENGTH_LONG).show();
    }


    @Override
    public void onError(String msg) {
        Log.d("aa", "onError()");
        Toast.makeText(MainActivity.this, "更新失败" + msg, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onDownloading() {
        Log.d("aa", "onDownloading()");
        Toast.makeText(MainActivity.this, "正在下载...", Toast.LENGTH_LONG)
                .show();
    }


    @Override
    public void hasNewVersion(boolean has) {
        Log.d("aa", "hasNewVersion()");
        if (has) {
        new AlertDialog.Builder(MainActivity.this).setTitle("系统提示")//设置对话框标题  
          
            .setMessage("检测到最新版本,是否需要更新!")//设置显示的内容  
         
            .setPositiveButton("确定",new DialogInterface.OnClickListener() {//添加确定按钮  
         @Override  
         public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件  
         
               manager.downLoad();
                         dialog.dismiss();
         
                }  
         
            }).setNegativeButton("返回",new DialogInterface.OnClickListener() {//添加返回按钮  
          @Override  
         public void onClick(DialogInterface dialog, int which) {//响应事件  
                    Log.i("alertdialog"," 请保存数据!");  
         
                }  
         
            }).show();//在按键响应事件中显示此对话框  
         
        }
    }
    
    
/**
* 获取版本号VersionCode
*/
public int getVersionCode(Context context)//获取版本号(内部识别号)
{
try {
PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pi.versionCode;
} catch (PackageManager.NameNotFoundException e) {


e.printStackTrace();
return 0;
}
}


}






public class VersionManager {


private Context context;
   private AppVersion appVersion;
   private DownloadManager downloadManager;
   private SharedPreferences prefs;
   private static final String DL_ID = "update_app_id";
   public  Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
 
   // 文件在sd卡的真实目录
   private String apkAbsolutePath;


   public void setOnUpdateListener(OnUpdateListener listener) {
       this.listener = listener;
   }


   private OnUpdateListener listener;


   public void setAppVersion(AppVersion appVersion) {
       this.appVersion = appVersion;
   }


   private static VersionManager instance = null;


   public static VersionManager getInstance(Context context,
                                            AppVersion appVersion) {
       if (instance == null) {
           instance = new VersionManager(context, appVersion);
       }
       return instance;
   }


   private VersionManager(Context context, AppVersion appVersion) {
       this.appVersion = appVersion;
       this.context = context;
       apkAbsolutePath = getSDPath() + appVersion.getFilePath() + "/"
               + appVersion.getFileName();
       downloadManager = (DownloadManager) context
               .getSystemService(Context.DOWNLOAD_SERVICE);
       prefs = PreferenceManager.getDefaultSharedPreferences(context);
   }


   public void checkUpdateInfo() {//根据是否存在下载链接
       String localVersion=appVersion.getApkUrl();
       if(localVersion.equals(appVersion.getApkUrl())){//有新版本
           listener.hasNewVersion(true);
       }else{//没有新版本
           listener.hasNewVersion(false);
       }


    /*   String localVersion = Utils.getVersionCode(context) + "";
       // 这里只要两个版本不一致就更新,不考虑版本降级的情况...
       if (!localVersion.equals(appVersion.getVersionCode())) {
           listener.hasNewVersion(true);
       } else {
           listener.hasNewVersion(false);
       }*/
   }


  




   public void  queryDownloadStatus(){
       DownloadManager.Query query = new DownloadManager.Query();
       query.setFilterById(prefs.getLong(DL_ID, 0));
       Log.d("status","downloadManagerId="+Long.toString(prefs.getLong(DL_ID, 0)));
       Cursor c = downloadManager.query(query);
       if (c.moveToFirst()) {
           int status = c.getInt(c
                   .getColumnIndex(DownloadManager.COLUMN_STATUS));
           switch (status) {
               case DownloadManager.STATUS_RUNNING:
                   // 正在下载,不做任何事情
                   Log.d("manager","STATUS_RUNNING()");
                   listener.onDownloading();
                   break;
               case DownloadManager.STATUS_SUCCESSFUL:
                   Log.d("manager","STATUS_SUCCESSFUL()");
                   // 下载完成首先取消注册广播,然后安装app
                   listener.onSuccess();
                   context.unregisterReceiver(receiver);
                   installApk();
                   break;
               case DownloadManager.STATUS_FAILED:
                   Log.d("manager","STATUS_FAILED()");
                   // 下载失败 清除已下载的内容,重新下载
                   context.unregisterReceiver(receiver);
                   listener.onError("下载失败,请重试");
                   downloadManager.remove(prefs.getLong(DL_ID, 0));
                   prefs.edit().clear().commit();
                   break;
           }
       }
   }


   /**
    * 下载文件
    */
   public void downLoad() {
       if (!isSdCardExist()) {
           listener.onError("文件无法下载请检测您的sd卡");
           return;
       }
       if (isFileExist(apkAbsolutePath)) {
           // 如果文件已经存在则安装app
           installApk();
           return;
       }
       // 开始下载
       Uri resource = Uri.parse(appVersion.getApkUrl());
       DownloadManager.Request request = new DownloadManager.Request(resource);
       request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
               | DownloadManager.Request.NETWORK_WIFI);
       request.setAllowedOverRoaming(false);
       // 设置文件类型
       MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
       String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap
               .getFileExtensionFromUrl(appVersion.getApkUrl()));
       request.setMimeType(mimeString);
       // 在通知栏中显示
       request.setNotificationVisibility(View.VISIBLE);
       request.setVisibleInDownloadsUi(true);
       request.setDestinationInExternalPublicDir(
               "/" + appVersion.getFilePath() + "/", appVersion.getFileName());
       request.setTitle("QQ");
       long id = downloadManager.enqueue(request);


      /* downloadObserver = new DownloadChangeObserver(null);
       context.getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);*/


       // 保存id
       prefs.edit().putLong(DL_ID, id).commit();
       // 注册广播监听下载
       context.registerReceiver(receiver, new IntentFilter(
               DownloadManager.ACTION_DOWNLOAD_COMPLETE));
   }


   private void installApk() {//安装apk
       Intent intent = new Intent(Intent.ACTION_VIEW);
       intent.setDataAndType(Uri.fromFile(new File(apkAbsolutePath)), "application/vnd.android.package-archive");
       context.startActivity(intent);
   }


   private boolean isSdCardExist() {
       return Environment.getExternalStorageState().equals(
               Environment.MEDIA_MOUNTED);
   }


   private String getSDPath() {
       if (isSdCardExist()) {
           return Environment.getExternalStorageDirectory() + "/";
       }
       return null;
   }


   private boolean isFileExist(String path) {
       return new File(path).exists();
   }


   private BroadcastReceiver receiver = new BroadcastReceiver() {
       @Override
       public void onReceive(Context context, Intent intent) {
           queryDownloadStatus();
       }
   };


   /**
    * app版本信息
    *
    * @author sunger
    *
    */
   public static class AppVersion {
       // apk下载url
       private String apkUrl;
       // apk最新版本
       private int versionCode;


       public int getVersionCode() {
           return versionCode;
       }


       public void setVersionCode(int versionCode) {
           this.versionCode = versionCode;
       }


       public String getFileName() {
           return fileName;
       }


       public void setFileName(String fileName) {
           this.fileName = fileName;
       }


       private String fileName;


       public String getFilePath() {
           return filePath;
       }


       public void setFilePath(String filePath) {
           this.filePath = filePath;
       }


       /**
        * 文件在sd卡的相对路径
        */
       private String filePath;


       public String getApkUrl() {
           return apkUrl;
       }


       public void setApkUrl(String apkUrl) {
           this.apkUrl = apkUrl;
       }


   }


   public interface OnUpdateListener {
       /**
        * 是否有新版本更新,如果为true这里开始调用
        *
        * @param has
        */
       public void hasNewVersion(boolean has);


       /**
        * 正在开始下载
        */
       public void onDownloading();


       /**
        * 下载完成,并且安装成功
        */
       public void onSuccess();


       /**
        * 更新失败
        *
        * @param msg
        *            失败的消息
        */
       public void onError(String msg);


   }


}







/**
 * Created by Shi on 2017/2/7.
 * 检查版本更新
 */
public class CheckUpdate extends AsyncTask<String, Void, String> {
    private int versionCode;
    private Context context;
    private Handler handler;
     public  CheckUpdate(Handler handler,Context context, int versionCode){
         this.context=context;
         this.handler=handler;
        this.versionCode=versionCode;
    }


    @Override
    protected String doInBackground(String... strings) {
        String result = null;


        try {
            Log.d("CheckUpdate","versionCode=="+versionCode);
//            result = FocusService.getInstance(context).doCheckUpdate(String.valueOf(versionCode));网络请求结果
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
//        if(null !=result){
            Log.d("CheckUpdate","result="+result);
            Message message=Message.obtain();
            message.what=021;
//            message.obj=result;
            message.obj="http://222.73.3.43/sqdd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk?mkey=5523a9bb6eb200cf&f=188a&p=.apk";//给一个假值
            handler.sendMessage(message);


//        }
//        else{
//            Log.d("CheckUpdate","失败");
//        }
    }
}






Demo下载地址:http://download.csdn.net/detail/sinat_28238111/9750008


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值