日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android 版本检测更新

發布時間:2023/12/9 Android 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android 版本检测更新 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Android版本檢測更新是每個應用升級所不可少的,以前早就做過一些,一直沒有時間與大家分享,現在就跟大家來分享一下我做的版本檢測更新吧。先上圖

點擊更新之后的

可能有人會問為啥點擊更新提示框不消失啊,可以根據自己的情況而定,有的需要強制更新,也是為了方便用戶看到下載的進度。我這里只是為了測試一下效果而已。真正的是點擊更新以后會在通知欄里面進行顯示的 效果就是這樣的

也有的可能需要在桌面上面展示給用戶,下面的效果

這些都是是需求而定的。不多說了上代碼

package com.liuyongxiang.update.activity;import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL;import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.json.JSONException; import org.json.JSONObject;import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.liuyongxiang.update.R; import com.liuyongxiang.update.bean.VersionBean; import com.liuyongxiang.update.utils.MyConstants; import com.liuyongxiang.update.utils.SpTools; import com.liuyongxiang.update.view.NumberProgressBar; import com.liuyongxiang.update.view.OnProgressBarListener;import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.PixelFormat; import android.graphics.pdf.PdfDocument; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import android.text.method.ScrollingMovementMethod; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.RemoteViews; import android.widget.TextView; import android.widget.Toast;@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SplashActivity extends Activity implements OnProgressBarListener {private static final int LOADMAIN = 1;// 加載主界面private static final int SHOWUPDATEDIALOG = 2;// 顯示是否更新的對話框protected static final int ERROR = 3;// 錯誤統一代號private RelativeLayout rl_root;// 界面的根布局組件private int versionCode;// 版本號private String versionName;// 版本名private TextView tv_versionName;// 顯示版本名的組件private VersionBean parseJson;// url信息封裝beanprivate long startTimeMillis;// 記錄開始訪問網絡的時間private NumberProgressBar pb_download;// 下載最新版本apk的進度條private Notification.Builder mBuilder;private NotificationManager mNotificationManager;public static final int NOTIFICATION_ID = 200; // 通知唯一idpublic static final int MUTE = 0; // 0表示靜音public static final int VIBRATE = 1; // 1表示震動public static final int SOUND = 2; // 2表示響音@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 初始化界面initView();// 初始化數據initData();//如果正常的從服務器獲取應調用下面的timeInitialization(),而showUpdateDialog()只是為了測試查看一下效果// timeInitialization();showUpdateDialog();}/*** 耗時的功能封裝,只要耗時的處理,都放到此方法*/private void timeInitialization() {// 一開始動畫,就應該干耗時的業務(網絡,本地數據初始化,數據的拷貝等)if (SpTools.getBoolean(getApplicationContext(), MyConstants.AUTOUPDATE,false)) {// true 自動更新// 檢測服務器的版本checkVerion();}// 增加自己的耗時功能處理}private void initData() {// 獲取自己的版本信息PackageManager pm = getPackageManager();try {PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);// 版本號versionCode = packageInfo.versionCode;// 版本名versionName = packageInfo.versionName;// 設置textviewtv_versionName.setText(versionName);} catch (NameNotFoundException e) {// can not reach 異常不會發生}}private void checkVerion() {// 耗時操作都要放到子線程中執行new Thread(new Runnable() {@Overridepublic void run() {BufferedReader bfr = null;HttpURLConnection conn = null;int errorCode = -1;// 正常,沒有錯誤try {startTimeMillis = System.currentTimeMillis();URL url = new URL("http://10.0.2.2:8080/guardversion.json");conn = (HttpURLConnection) url.openConnection();// 讀取數據的超時時間conn.setReadTimeout(5000);// 網絡連接超時conn.setConnectTimeout(5000);// 設置請求方式// 獲取相應結果int code = conn.getResponseCode();if (code == 200) {// 數據獲取成功// 獲取讀取的字節流InputStream is = conn.getInputStream();// 把字節流轉換成字符流bfr = new BufferedReader(new InputStreamReader(is));// 讀取一行信息String line = bfr.readLine();// json字符串數據的封裝StringBuilder json = new StringBuilder();while (line != null) {json.append(line);line = bfr.readLine();}parseJson = parseJson(json);// 返回數據封裝信息} else {errorCode = 404;}} catch (MalformedURLException e) {// 4002errorCode = 4002;e.printStackTrace();} catch (IOException e) {// 4001errorCode = 4001;e.printStackTrace();} catch (JSONException e) {errorCode = 4003;e.printStackTrace();} finally {Message msg = Message.obtain();if (errorCode == -1) {msg.what = isNewVersion(parseJson);// 檢測是否有新版本} else {msg.what = ERROR;msg.arg1 = errorCode;}long endTime = System.currentTimeMillis();if (endTime - startTimeMillis < 3000) {SystemClock.sleep(3000 - (endTime - startTimeMillis));// 時間不超過3秒,補足3秒}handler.sendMessage(msg);// 發送消息try {// 關閉連接資源if (bfr != null) {bfr.close();}if (conn != null) {conn.disconnect();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}).start();}private Handler handler = new Handler() {public void handleMessage(android.os.Message msg) {// 處理消息switch (msg.what) {case LOADMAIN:// 加載主界面loadMain();break;case ERROR:// 有異常switch (msg.arg1) {case 404:// 資源找不到Toast.makeText(getApplicationContext(), "404資源找不到", 0).show();break;case 4001:// 找不到網絡Toast.makeText(getApplicationContext(), "4001沒有網絡", 0).show();break;case 4003:// json格式錯誤Toast.makeText(getApplicationContext(), "4003json格式錯誤", 0).show();break;default:break;}loadMain();// 進入主界面break;case SHOWUPDATEDIALOG:// 顯示更新版本的對話框showUpdateDialog();break;default:break;}}};private AlertDialog dialog;private void loadMain() {Intent intent = new Intent(SplashActivity.this, MainActivity.class);startActivity(intent);// 進入主界面finish();// 關閉自己};protected int isNewVersion(VersionBean parseJson) {// 獲取服務器設置的版本// int serverCode = parseJson.getVersionCode();int serverCode = 2;// 獲取服務器的版本System.out.println("serverCode----->" + serverCode);if (serverCode == versionCode) {// 如果版本一致直接進入到主界面return LOADMAIN;/** 進入主界面 Message msg = Message.obtain(); msg.what = LOADMAIN;*/} else {// 否則會彈出提示更新的提示框return SHOWUPDATEDIALOG;}}/*** 顯示是否更新新版本的對話框*/public void showUpdateDialog() {dialog = new AlertDialog.Builder(this).create();dialog.setCancelable(false);dialog.show();Window window = dialog.getWindow();window.setContentView(R.layout.prompt_alertdialog);LinearLayout ll_title = (LinearLayout) window.findViewById(R.id.ll_title);ll_title.setVisibility(View.VISIBLE);TextView tv_title = (TextView) window.findViewById(R.id.tv_title);pb_download = (NumberProgressBar) window.findViewById(R.id.pb_splash_download);pb_download.setVisibility(View.GONE);// 隱藏進度條pb_download.setOnProgressBarListener(this);tv_title.setText("版本更新");TextView tv_content = (TextView) window.findViewById(R.id.tv_content);tv_content.setMovementMethod(new ScrollingMovementMethod());tv_content.setText("是否更新新版本?新版本的具有如下特性:1.是否更新新版本?新版本的具有如下特性 2.是否更新新版本?新版本的具有如下特性 3.是否更新新版本?新版本的具有如下特性 4.是否更新新版本?新版本的具有如下特性 5.是否更新新版本?新版本的具有如下特性 6.是否更新新版本?新版本的具有如下特性 7.是否更新新版本?新版本的具有如下特性 8.是否更新新版本?新版本的具有如下特性");final TextView tv_sure = (TextView) window.findViewById(R.id.tv_sure);final TextView tv_cancle = (TextView) window.findViewById(R.id.tv_cancle);tv_cancle.setText("取消");tv_cancle.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {loadMain();dialog.cancel();}});tv_sure.setText("更新");tv_sure.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {downLoadNewApk();// 下載新版本createFloatView();tv_cancle.setEnabled(false);tv_sure.setEnabled(false);dialog.cancel();loadMain();pb_download.setVisibility(View.VISIBLE);}});}/*** 新版本的下載安裝*/protected void downLoadNewApk() {HttpUtils utils = new HttpUtils();// parseJson.getUrl() 下載的url// target 本地路徑// System.out.println(parseJson.getUrl());File file = new File("/mnt/sdcard/測試.apk");//如果此文件已存在先刪除file.delete();// 刪除文件utils.download("http://www.gamept.cn/d/file/game/qipai/20140627/HappyLordZZ_1.0.19_20140325_300002877528_2200139763.apk","/mnt/sdcard/測試.apk", new RequestCallBack<File>() {@Overridepublic void onLoading(final long total, final long current,boolean isUploading) {pb_download.setVisibility(View.VISIBLE);// 設置進度的顯示int max = (int) total;int progress = (int) current;pb_download.setMax(max);// 設置進度條的最大值pb_download.setProgress(progress);// 設置當前進度pb_download2.setMax(max);pb_download2.setProgress(progress);// showNotification(max,progree);showNotifi(max, progress);super.onLoading(total, current, isUploading);}@Overridepublic void onSuccess(ResponseInfo<File> arg0) {// 下載成功// 在主線程中執行Toast.makeText(getApplicationContext(), "下載新版本成功", 1).show();// 安裝apkinstallApk();// 安裝apkpb_download.setVisibility(View.GONE);// 隱藏進度條rl_notification.setVisibility(View.GONE);}@Overridepublic void onFailure(HttpException arg0, String arg1) {// 下載失敗Toast.makeText(getApplicationContext(), "下載新版本失敗", 1).show();pb_download.setVisibility(View.GONE);// 隱藏進度條}});}private NumberProgressBar pb_download2;private RelativeLayout rl_notification;/*** 安裝下載的新版本*/protected void installApk() {Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");String type = "application/vnd.android.package-archive";Uri data = Uri.fromFile(new File("/mnt/sdcard/測試.apk"));intent.setDataAndType(data, type);startActivityForResult(intent, 0);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// 如果用戶取消更新apk,那么直接進入主界面loadMain();super.onActivityResult(requestCode, resultCode, data);}/*** @param jsonString* url的json數據* @return url信息封裝對象* @throws JSONException*/protected VersionBean parseJson(StringBuilder jsonString)throws JSONException {VersionBean bean = new VersionBean();JSONObject jsonObj;jsonObj = new JSONObject(jsonString + "");int versionCode = jsonObj.getInt("version");String url = jsonObj.getString("url");String desc = jsonObj.getString("desc");// 封裝結果數據bean.setDesc(desc);bean.setUrl(url);bean.setVersionCode(versionCode);return bean;}/*** 初始化界面*/private void initView() {setContentView(R.layout.activity_main);rl_root = (RelativeLayout) findViewById(R.id.rl_splash_root);tv_versionName = (TextView) findViewById(R.id.tv_splash_version_name);}@Overridepublic void onProgressChange(int current, int max) {pb_download.setProgress(current);pb_download2.setProgress(current);}private void createFloatView() {final WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();getApplication();final WindowManager mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);wmParams.type = LayoutParams.TYPE_PHONE;wmParams.format = PixelFormat.RGBA_8888;wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE;wmParams.gravity = Gravity.LEFT | Gravity.TOP;wmParams.x = 0;wmParams.y = 0;wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;LayoutInflater inflater = LayoutInflater.from(getApplication());final View mFloatLayout = inflater.inflate(R.layout.activity_notification, null);mWindowManager.addView(mFloatLayout, wmParams);rl_notification = (RelativeLayout) mFloatLayout.findViewById(R.id.rl_notification);pb_download2 = (NumberProgressBar) mFloatLayout.findViewById(R.id.pb_download);// TextView tv_name = (TextView)// mFloatLayout.findViewById(R.id.tv_name);// TextView tv_time = (TextView)// mFloatLayout.findViewById(R.id.tv_time);// ImageView iv_icon = (ImageView)// mFloatLayout.findViewById(R.id.iv_icon);// 系統顯示的通知圖片mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));rl_notification.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {wmParams.x = (int) event.getRawX()- rl_notification.getMeasuredWidth() / 2;wmParams.y = (int) event.getRawY()- rl_notification.getMeasuredHeight() / 2 - 25;mWindowManager.updateViewLayout(mFloatLayout, wmParams);return false;}});}private void showNotification(final int total, final int current) {mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);mBuilder = new Notification.Builder(SplashActivity.this);LayoutInflater inflater = LayoutInflater.from(getApplication());View view = inflater.inflate(R.layout.activity_notification, null);mBuilder.setContentTitle("這是測試").setContentText("下載中...").setSmallIcon(R.drawable.app_icon);new Thread(new Runnable() {@SuppressLint("NewApi")@Overridepublic void run() {mBuilder.setProgress(total, current, false);mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());if (current / total == 1) {mNotificationManager.cancel(0);}}}).start();}private void showNotifi(final int total, final int current) {NotificationManager notiManage;Notification note;mBuilder = new Notification.Builder(SplashActivity.this);notiManage = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);note = new Notification();note.flags = Notification.FLAG_AUTO_CANCEL;RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.activity_notifi);contentView.setTextViewText(R.id.notificationTitle, "這是測試");String str_progress =current*100/total+"%"; contentView.setTextViewText(R.id.notificationPercent, str_progress);contentView.setProgressBar(R.id.notificationProgress, total, current,false);note.contentView = contentView;note.tickerText = "正在下載";note.icon = R.drawable.app_icon;PendingIntent p = PendingIntent.getActivity(SplashActivity.this, 0,new Intent(Intent.ACTION_VIEW), 0);// 這個非要不可。note.contentIntent = p;notiManage.notify(NOTIFICATION_ID, note);if (current / total == 1) {notiManage.cancelAll();}} }

這只是一些簡單的代碼,如果想測試一下具體效果
點擊免費下載源碼
如果有問題請加Android交流群 470707794或留言

總結

以上是生活随笔為你收集整理的Android 版本检测更新的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。