版本更新在后台需要慢慢进行,所以IntentService很适合进行版本的更新操作,需要的技术:广播 服务
1.写一个服务类 用于检查是否有版本的更新,如果有新版本的话发个广播 该广播用于进行弹出对话框让用户进行选择下载或者是忽略
package com.yafeng.service; import android.app.AlertDialog; import android.app.Dialog; import android.app.IntentService; import android.content.DialogInterface; import android.content.Intent; import android.util.Log; import android.widget.Toast; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.GsonBuilder; import com.yafeng.activity.LoginActivity; import com.yafeng.activity.MainActivity; import com.yafeng.dao.DbUtils; import com.yafeng.entity.Order; import com.yafeng.entity.ThreeAddress; import com.yafeng.entity.User; import com.yafeng.entity.VersionEntity; import com.yafeng.http.HttpConfig; import com.yafeng.http.OkManager; import com.yafeng.http.execption.OkHttpException; import com.yafeng.http.request.CommonRequest; import com.yafeng.http.request.RequestParams; import com.yafeng.http.response.JsonCallback; import com.yafeng.utils.GsonBean; import com.yafeng.utils.GsonBeanList; import com.yafeng.utils.PackAgesUtils; import org.greenrobot.greendao.query.QueryBuilder; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.Request; /** * Created by Administrator on 2017-01-04. */ public class CheckVersionService extends IntentService{ private static final String TAG = CheckVersionService.class.getSimpleName(); public static String RECEIVER_CHECK_VERSION = "com.yafeng.service.CheckVersionService"; /** * Creates an IntentService. Invoked by your subclass's constructor. * * to name the worker thread, important only for debugging. */ public CheckVersionService() { super("CheckVersionService"); } @Override protected void onHandleIntent(Intent intent) { Log.i(TAG, "CheckVersionService onHandleIntent"); int fromSource = intent.getIntExtra("fromSource", 0); int version = PackAgesUtils.getVersionCode(this); Log.e("ZS","版本号:"+version); checkVersion(version);
} /** * 检查版本更新 */ protected void checkVersion(int version){
Map<String,String> map = new HashMap<>(); map.put("version",version); Request request = CommonRequest.postRequest(HttpConfig.BASE_URL+ HttpConfig.CHECK_VERSION,new RequestParams(map)); OkManager.post(request, new JsonCallback() { @Override public void onFaile(OkHttpException e) { Log.e("ZS","错误:"+e.getEcode()+e.getEmsg()); } @Override public void onSuccess(String json) { Log.e("ZS","成功:"+json); Intent broad = new Intent(); broad.setAction(RECEIVER_CHECK_VERSION); try { JSONObject jsonObject=new JSONObject(json); int status=jsonObject.optInt("stauts"); if(status==7){ broad.putExtra("url", "error"); Log.e("ZS","检查版本错误"); }else if(status==9){ Log.e("ZS","当前为最新版本"); broad.putExtra("url","new"); }else if(status==8){ JSONObject jsonData=jsonObject.optJSONObject("data"); String url=jsonData.optString("url"); Log.e("ZS","需要网络获取最新版本"); broad.putExtra("url", url); } sendBroadcast(broad); } catch (JSONException e) { e.printStackTrace(); } } }); } } 2.广播接收类 用于接收版本更新服务类的数据 提示用户进行下载
class VersionReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Log.e(TAG, "VersionReceiver onReceive"); String url=intent.getStringExtra("url"); if(url.equals("error")){ toast("请求网络发生错误"); }else if(url.equals("new")){ toast("当前为最新版本"); }else if(url.startsWith("http")){ Log.e(TAG, "url:"+url); showNoticeDialog(url); }else if(url.equals("dialog_dismis")){ mProgressDialog.dismiss(); } } }
private ProgressDialog mProgressDialog; private Dialog noticeDialog; public void showNoticeDialog(final String url) { AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this); builder.setTitle("软件版本更新"); builder.setPositiveButton("下载", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent downIntent = new Intent(BaseActivity.this, DownloadApkService.class); downIntent.putExtra("url",url); startService(downIntent); mProgressDialog=new ProgressDialog(BaseActivity.this); mProgressDialog.setMessage("正在下载,请稍后..."); mProgressDialog.show(); } }); builder.setNegativeButton("退出", new DialogInterface.OnClickListener() //以后再说 { public void onClick(DialogInterface dialog, int which) { noticeDialog.dismiss(); } }); noticeDialog = builder.create(); if (!isFinishing()&¬iceDialog != null && !noticeDialog.isShowing()) { noticeDialog.show(); } } 3.下载服务类(如果用户选择下载之后进行后台任务的下载工作 下载完成后发广播告诉广播接收者已经下载 完毕,并结束进度条)
package com.yafeng.service; import android.app.IntentService; import android.app.ProgressDialog; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * apk下载服务类 * Created by Administrator on 2017-01-04. */ public class DownloadApkService extends IntentService{ private static final String TAG=DownloadApkService.class.getSimpleName(); private static final String savePath = Environment .getExternalStorageDirectory().getAbsolutePath() + "/yfApp"; private static final String saveFileName = savePath + "/yf.apk"; private ProgressDialog dialog=null; /** * Creates an IntentService. Invoked by your subclass's constructor. * * */ public DownloadApkService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { Log.i(TAG, "DownloadApkService onHandleIntent"); String apkUrl = intent.getStringExtra("url"); try { URL url = new URL(apkUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); // int length = conn.getContentLength(); InputStream is = conn.getInputStream(); File file = new File(savePath); if (!file.exists()) { file.mkdirs(); } String apkFile = saveFileName; File ApkFile = new File(apkFile); if (!ApkFile.exists()) { ApkFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(ApkFile); byte[] buf = new byte[1024]; int len = 0; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); fos.flush(); } fos.close(); is.close(); Intent broad = new Intent(); broad.setAction(CheckVersionService.RECEIVER_CHECK_VERSION); broad.putExtra("url", "dialog_dismis"); sendBroadcast(broad); installApk(); } catch (Exception e) { e.printStackTrace(); Log.v("Error", e.getMessage()); } } /** * 安装apk * */ private void installApk() { File apkfile = new File(saveFileName); if (!apkfile.exists()) { return; } Log.e("安装Apk","安装Apk"); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive"); //安装时加此句 否则出现异常 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(intent); } }
4.进行广播的注册 和服务的注册
public void registerVersionBroad(){ IntentFilter filt = new IntentFilter(CheckVersionService.RECEIVER_CHECK_VERSION); versionReceiver = new VersionReceiver(); registerReceiver(versionReceiver, filt); Log.i(TAG, "registerVersionBroad"); }
<service android:name=".service.CheckVersionService"></service> <service android:name=".service.DownloadApkService"></service>
5.检查版本的更新 开启服务
private void checkVersion(){ Intent verService = new Intent(this, CheckVersionService.class); verService.putExtra("fromSource", 0); startService(verService); }