因为工作的需求需要实现版本更新。
情景:用户打开apk之后检查版本,新版本提示更新,点击之后在通知栏提示正在下载,并且显示更新进度。
废话不说上代码:
1:定义一个intentservice:
public class UpdateApkIntentService extends IntentService { // TODO: Rename actions, choose action names that describe tasks that this private static final int NOTIFY_DOW_ID = 0; private static final int NOTIFY_OK_ID = 1; private SharedPreferenceUtil sp; private Context mContext = this; private boolean cancelled; private int oldprocess; private NotificationManager mNotificationManager; private Notification mNotification; File downapkfile; RemoteViews contentView; private String apkurl; private JindianziApplication jindianziApplication; public UpdateApkIntentService() { super("UpdateApkIntentService"); } /** * Starts this service to perform action Foo with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ // TODO: Customize helper method public static void startActionFoo(Context context, String param1, String param2) { Intent intent = new Intent(context, UpdateApkIntentService.class); context.startService(intent); } /** * Starts this service to perform action Baz with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ // TODO: Customize helper method public static void startActionBaz(Context context, String param1, String param2) { Intent intent = new Intent(context, UpdateApkIntentService.class); context.startService(intent); } @Override public void onCreate() { super.onCreate(); // 做一些准备性的工作。 sp = new SharedPreferenceUtil(getApplicationContext()); mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE); cancelled = true; Log.d("intentservice","onCreate"); } @Override protected void onHandleIntent(Intent intent) { // 判断网络 apkurl = intent.getExtras().getString("apkurl"); apkurl = intent.getStringExtra("apkurl"); if(isNetworkConnected(getApplicationContext())){ // sp.setisLoad("isLoad",true); createNotification(NOTIFY_DOW_ID); try { DownApk(apkurl); } catch (MalformedURLException e) { e.printStackTrace(); } }else { Toast.makeText(getApplicationContext(),"网络不好,请检查网络",Toast.LENGTH_SHORT).show(); } // } // Log.d("intentservice","onHandleIntent"); } // 判断下载的三种状态下载中,下载失败,下载完成 @Override public int onStartCommand(Intent intent, int flags, int startId) { flags = START_STICKY; return super.onStartCommand(intent, flags, startId); } @Override public void setIntentRedelivery(boolean enabled) { super.setIntentRedelivery(true); } private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 0: // 更新进度 RemoteViews contentView = mNotification.contentView; contentView.setTextViewText(id.content_view_text1, "xxx"); contentView.setProgressBar(id.content_view_progress, 100, msg.arg1, false); // 更新UI mNotificationManager.notify(NOTIFY_DOW_ID, mNotification); break; case 1: mNotificationManager.cancel(NOTIFY_DOW_ID); createNotification(NOTIFY_OK_ID); // sp.setisLoad("isLoad",false); break; } }; }; /** * 创建通知 */ private void createNotification(int notifyId) { switch (notifyId) { case NOTIFY_DOW_ID: int icon = drawable.default_icon; CharSequence tickerText = "开始下载..."; long when = System.currentTimeMillis(); mNotification = new Notification(icon, tickerText, when); mNotification.icon= drawable.logo_new; // 放置在"正在运行"栏目中 mNotification.flags = Notification.FLAG_ONGOING_EVENT; RemoteViews contentView = new RemoteViews(mContext.getPackageName(), layout.notice_loadapk); contentView.setTextViewText(id.content_view_text1,"开始下载..."); contentView.setProgressBar(id.content_view_progress, 100, 0, false); mNotification.contentView = contentView; mNotificationManager.notify(notifyId, mNotification); break; case NOTIFY_OK_ID: // System.out.println("下载完成之后进入通知。"); // int icon2 = drawable.default_icon; // CharSequence tickerText2 = "下载完毕"; // long when2 = System.currentTimeMillis(); // mNotification = new Notification(icon2, tickerText2, when2); // mNotification.icon = drawable.logo_new; // //放置在"通知形"栏目中 // mNotification.flags = Notification.FLAG_AUTO_CANCEL; // PendingIntent contentInten2 = PendingIntent.getActivity(mContext, 0, null, 0); // mNotification.setLatestEventInfo(mContext, "下载完成", "文件已下载完毕", contentInten2); // Toast.makeText(UpdateApkIntentService.this, "下载完成", Toast.LENGTH_SHORT).show(); // mNotificationManager.notify(notifyId, mNotification); installapk(getApplicationContext(),downapkfile); break; } } //发送消息进行更新进度条 public void sendMessage(int what,int mprogress) { Message msg0 = handler.obtainMessage(); msg0.what = what; msg0.arg1 = mprogress; handler.sendMessage(msg0); } // 下载文件 private void DownApk(String url) throws MalformedURLException { String urlStr=url; oldprocess = 0; try {
// 屏蔽HTTPS证书验证 SSLContext sc =SSLContext.getInstance("TLS"); sc.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier()); HttpsURLConnection conn = (HttpsURLConnection)new URL(urlStr).openConnection(); // HttpURLConnection conn = (HttpURLConnection)new URL(urlStr).openConnection(); conn.setDoOutput(true); conn.setDoInput(true); // 删除文件夹 File apkfile = new File("/sdcard/xxx.apk"); if (apkfile.exists()){ apkfile.delete(); } final String fileName = "xxx.apk"; File tmpFile = new File("/sdcard/"); if (!tmpFile.exists()) { tmpFile.mkdir(); } downapkfile = new File("/sdcard/", fileName); try { downapkfile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } InputStream is = conn.getInputStream(); //内容总长度 long contentlength = conn.getContentLength(); //已下载的长度 long loadedlength = 0; System.out.println(contentlength+""); FileOutputStream fileOutput= new FileOutputStream(downapkfile); byte[] buf = new byte[512];//分配byte conn.connect(); double count = 0; if (conn.getResponseCode() >= 400) { } else { while (count <= 100) { if (is != null) { int numRead = is.read(buf); if (numRead <= 0) { sendMessage(1,0); break; } else { // 设置进度 fileOutput.write(buf, 0, numRead); loadedlength += numRead; int mprogress = (int) ((loadedlength*100)/contentlength); // 设置下载进度,更新 // 设置通知发送消息给NOtifyManager进行更新(进度更新,状态更新),判断状态 if(oldprocess <= mprogress-2 ){ // 避免notifymanager ANR,每下载百分之2才进行通知一次 oldprocess =mprogress; sendMessage(0, mprogress); } } } else { break; } } } conn.disconnect();//记得关闭连接 fileOutput.close(); is.close(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override public boolean onUnbind(Intent intent) { // sp.setisLoad("isLoad", false); //// mNotificationManager.cancel(NOTIFY_OK_ID); // mNotificationManager.cancelAll(); // sendMessage(0, 0); // Log.d("intentservice", "onUnbind"); return super.onUnbind(intent); } // 主要判断wifi和手机网络(3G+4G网络)是否存在一个 public boolean isNetworkConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); NetworkInfo mWiFiNetworkInfo = mConnectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mMobileNetworkInfo = mConnectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mNetworkInfo != null&&(mWiFiNetworkInfo!=null || mMobileNetworkInfo != null)) { return mNetworkInfo.isAvailable(); } } return false; } // 安装apk private void installapk(Context ctxContext,File apkurl){ System.out.println("installapk"+apkurl.getPath()); Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(downapkfile), "application/vnd.android.package-archive"); ctxContext.startActivity(intent); } /** * Handle action Foo in the provided background thread with the provided * parameters. */ private void handleActionFoo(String param1, String param2) { // TODO: Handle action Foo throw new UnsupportedOperationException("Not yet implemented"); } /** * Handle action Baz in the provided background thread with the provided * parameters. */ private void handleActionBaz(String param1, String param2) { throw new UnsupportedOperationException("Not yet implemented"); } }
启动服务:
Uri uri = Uri.parse(Contans.UPDATE_VERSION); Intent intent = new Intent(xxx.this, UpdateApkIntentService.class); intent.putExtra("apkurl", uri.toString()); startService(intent);