Android 6.0 7.0 8.0 一个简单的app内更新版本-okgo app版本更新
生活随笔
收集整理的這篇文章主要介紹了
Android 6.0 7.0 8.0 一个简单的app内更新版本-okgo app版本更新
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?登陸時splash初始頁調(diào)用接口檢查app版本。如有更新,使用okGo的文件下載,保存到指定位置,調(diào)用Android安裝apk。
?
<!-- Android 8.0 (Android O)為了針對一些流氓軟件引導(dǎo)用戶安裝其他無關(guān)應(yīng)用。在應(yīng)用權(quán)限設(shè)置的“特殊訪問權(quán)限”中,加入了“安裝其他應(yīng)用”的設(shè)置 --><uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>?
?
package com.test.activity.sys;import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.AlertDialog; import android.text.format.Formatter; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.TextView; import android.widget.Toast;import com.lzy.okgo.OkGo; import com.lzy.okgo.callback.FileCallback; import com.lzy.okgo.callback.StringCallback; import com.lzy.okgo.convert.FileConvert; import com.lzy.okgo.model.Progress; import com.lzy.okgo.model.Response; import com.test.BuildConfig; import com.test.Constant; import com.test.R; import com.test.activity.MainActivity; import com.test.activity.sys.LoginActivity; import com.test.util.DataUtils;import com.test.view.NumberProgressBar;import org.json.JSONException; import org.json.JSONObject;import java.io.File; import java.text.NumberFormat;/*** @author cralor* @date 2018/8/8* 啟動頁 Activity*/ public class SplashActivity extends Activity{public static final int INSTALL_APK_REQUESTCODE = 3;public static final int GET_UNKNOWN_APP_SOURCES = 7;private File apkFile;/*** 可以額外指定文件的下載目錄和下載完成后的文件名*/private String destFileDir = Environment.getExternalStorageDirectory() + FileConvert.DM_TARGET_FOLDER + "myAppDownload" + File.separator;private String destFileName = "myApp.apk";private Handler handler;private Context content;private TextView tvDownloadSize;private TextView tvProgress;private TextView tvNetSpeed;private NumberProgressBar pbProgress;private NumberFormat numberFormat;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {//去掉標(biāo)題欄 requestWindowFeature(Window.FEATURE_NO_TITLE);// getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,WindowManager.LayoutParams. FLAG_FULLSCREEN);super.onCreate(savedInstanceState);setContentView(R.layout.activity_splash);content = this;handler = new Handler(Looper.getMainLooper());numberFormat = NumberFormat.getPercentInstance();numberFormat.setMinimumFractionDigits(2);initView();}/*** 打開程序時判斷是否已經(jīng)登陸過,且token有效*/private void initView() {// ... handler.postDelayed(new Runnable() {@Overridepublic void run() {OkGo.<String>post(Constant.GET_VERSION).tag(1).execute(new StringCallback() {@Overridepublic void onSuccess(Response<String> response) {String data = response.body();String code = "";String sysVersion = "";try {JSONObject jsonObject = new JSONObject(data);code = jsonObject.get("code").toString();sysVersion = jsonObject.get("data").toString();} catch (JSONException e) {e.printStackTrace();}Log.v("data",""+code);if(Constant.SUCCESS_CODE.equals(code)){// Android studio 中 build.gradle 中的版本號// 獲取PackageManager的實(shí)例PackageManager packageManager = getPackageManager();// getPackageName()是你當(dāng)前類的包名,0代表是獲取版本信息PackageInfo packInfo = null;String appVersion = "";try {packInfo = packageManager.getPackageInfo(getPackageName(), 0);} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}if (packInfo != null) {appVersion = packInfo.versionName;}if(appVersion.equals(sysVersion)){Intent intent = new Intent(SplashActivity.this, MainActivity.class);startActivity(intent);finish();}else{Log.e("SplashActivity","需要更新版本到---"+sysVersion);Toast.makeText(content, "有新版本需要更新", Toast.LENGTH_SHORT).show();getVersion();}}}@Overridepublic void onError(Response<String> response) {Toast.makeText(content, "請求失敗", Toast.LENGTH_SHORT).show();Intent intent = new Intent(SplashActivity.this, LoginActivity.class);startActivity(intent);overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);finish();}});}}, 3);}/*** 更新彈出框*/public void getVersion(){//退出的確認(rèn)彈出框new AlertDialog.Builder(content).setTitle("提示").setMessage("請更新最新版本").setCancelable(false).setPositiveButton("確定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int whichButton) {Toast.makeText(content, "dianjixiazai ", Toast.LENGTH_SHORT).show();fileDownload();View view1 = getLayoutInflater().inflate(R.layout.update_app_progress, null);tvDownloadSize = view1.findViewById(R.id.downloadSize);tvProgress = view1.findViewById(R.id.tvProgress);tvNetSpeed = view1.findViewById(R.id.netSpeed);pbProgress = view1.findViewById(R.id.pbProgress);AlertDialog.Builder builder = new AlertDialog.Builder(content);builder.setTitle("正在下載");builder.setView(view1);builder.setCancelable(false);builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which) {finish();}});builder.create().show();}}).setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int whichButton) {finish();}}).show();}/*** 獲取服務(wù)器apk*/public void fileDownload() {//檢查是否獲得寫入權(quán)限,未獲得則向用戶請求。Android 7.0 以上需要動態(tài)獲取權(quán)限if (ActivityCompat.checkSelfPermission(SplashActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {//未獲得,向用戶請求ActivityCompat.requestPermissions(SplashActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);}OkGo.<File>get("https://app地址/app.apk").tag(1).headers("header1", "headerValue1").params("param1", "paramValue1")/** 文件目錄如果不指定,默認(rèn)下載的目錄為 sdcard/download/,文件名如果不指定,則按照以下規(guī)則命名:1.首先檢查用戶是否傳入了文件名,如果傳入,將以用戶傳入的文件名命名2.如果沒有傳入,那么將會檢查服務(wù)端返回的響應(yīng)頭是否含有Content-Disposition=attachment;filename=FileName.txt該種形式的響應(yīng)頭,如果有,則按照該響應(yīng)頭中指定的文件名命名文件,如FileName.txt3.如果上述響應(yīng)頭不存在,則檢查下載的文件url,例如:http://image.baidu.com/abc.jpg,那么將會自動以abc.jpg命名文件4.如果url也把文件名解析不出來,那么最終將以"unknownfile_" + System.currentTimeMillis()命名文件*/.execute(new FileCallback(""+destFileDir, ""+destFileName) {@Overridepublic void onSuccess(Response<File> response) {String absolutePath = response.body().getAbsolutePath();apkFile = response.body().getAbsoluteFile();Log.e("appInstall---", ""+absolutePath);//Android8.0 版本更新無法自動安裝問題解決if (Build.VERSION.SDK_INT >= 26) {//來判斷應(yīng)用是否有權(quán)限安裝apkLog.e("appInstall---", "android版本8.0以上");boolean installAllowed= getPackageManager().canRequestPackageInstalls();//有權(quán)限if (installAllowed) {//安裝apkLog.e("appInstall---", "有權(quán)限安裝apk");installApk(apkFile);} else {//無權(quán)限 申請權(quán)限Log.e("appInstall---", "無權(quán)限 申請權(quán)限");ActivityCompat.requestPermissions(SplashActivity.this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_APK_REQUESTCODE);}} else {Log.e("appInstall---", "android版本低于8.0");installApk(apkFile);}}@Overridepublic void onError(Response<File> response) {Throwable exception = response.getException();exception.printStackTrace();Log.e("eeeee", exception.getMessage());}@Overridepublic void downloadProgress(Progress progress) {System.out.println(progress);String downloadLength = Formatter.formatFileSize(getApplicationContext(), progress.currentSize);String totalLength = Formatter.formatFileSize(getApplicationContext(), progress.totalSize);tvDownloadSize.setText(downloadLength + "/" + totalLength);String speed = Formatter.formatFileSize(getApplicationContext(), progress.speed);tvNetSpeed.setText(String.format("%s/s", speed));tvProgress.setText(numberFormat.format(progress.fraction));pbProgress.setMax(10000);pbProgress.setProgress((int) (progress.fraction * 10000));}});}
/*** 權(quán)限申請回調(diào)* @param requestCode requestCode* @param permissions permissions* @param grantResults grantResults*/@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);switch (requestCode) {case INSTALL_APK_REQUESTCODE://有注冊權(quán)限且用戶允許安裝if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {Log.e("appInstall---", "有注冊權(quán)限且用戶允許安裝");installApk(apkFile);} else {//將用戶引導(dǎo)至安裝未知應(yīng)用界面。Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);Log.e("appInstall---", "將用戶引導(dǎo)至安裝未知應(yīng)用界面");}break;default:break;}}
/*** 將用戶引導(dǎo)至安裝未知應(yīng)用界面,允許安裝未知應(yīng)用后,回到當(dāng)前activity繼續(xù)安裝應(yīng)用* @param requestCode requestCode* @param resultCode resultCode* @param data data*/@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);Log.e("appInstall---", "將用戶引導(dǎo)至安裝未知應(yīng)用界面,允許安裝未知應(yīng)用后,回到當(dāng)前activity繼續(xù)安裝應(yīng)用");installApk(apkFile);}/*** 安裝APK* @param apkFile apkFile*/public void installApk(File apkFile){//判讀版本是否在7.0以上if(Build.VERSION.SDK_INT >= 24) {Log.e("appInstall---", "android版本7.");//在AndroidManifest中的android:authorities的值, BuildConfig.APPLICATION_ID = com.testUri apkUri = FileProvider.getUriForFile(content, BuildConfig.APPLICATION_ID+".provider", apkFile);
Intent install = new Intent(Intent.ACTION_VIEW);install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);install.setDataAndType(apkUri, "application/vnd.android.package-archive");startActivity(install);} else {Log.e("appInstall---", "android版本低于7.0");Intent install = new Intent(Intent.ACTION_VIEW);install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);startActivity(install);}finish();}/*** 調(diào)用默認(rèn)瀏覽器下載apk*/public void getApk(){Uri uri = Uri.parse("https://lighttruck.com.cn:8086/app.apk");Intent intent = new Intent(Intent.ACTION_VIEW, uri);startActivity(intent);}}
?
?
activity_splash.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:gravity="center"tools:context="com.test.activity.sys.SplashActivity"></LinearLayout>
?
初始頁面自定義主題 <!-- 加載頁面 --> <activityandroid:name=".activity.sys.SplashActivity"android:theme="@style/SplashTheme"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter> </activity>
?
<style name="SplashTheme" parent="AppBaseTheme"><!-- 歡迎頁背景引用剛才寫好的 --><item name="android:windowBackground">@drawable/splash</item><item name="android:windowFullscreen">true</item><!-- <item name="android:windowIsTranslucent">true</item> --> <!-- 透明背景 --></style>?
update_app_progress.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:id="@+id/update_app_progress"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="@color/bg_gray"android:orientation="vertical" ><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="20dp"android:layout_marginTop="10dp"><TextViewandroid:id="@+id/downloadSize"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:text="--M/--M"android:textSize="10sp"/><TextViewandroid:id="@+id/netSpeed"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:layout_marginRight="10dp"android:text="---K/s"android:textSize="10sp"/><TextViewandroid:id="@+id/tvProgress"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:text="--.--%"android:textSize="10sp"/></RelativeLayout><com.test.view.NumberProgressBarandroid:id="@+id/pbProgress"android:layout_width="match_parent"android:layout_height="wrap_content"app:progress_reached_bar_height="1.5dp"app:progress_reached_color="#3498DB"app:progress_text_color="#3498DB"app:progress_text_size="10sp"app:progress_unreached_bar_height="0.75dp"app:progress_unreached_color="#CCCCCC"/> </LinearLayout>
?
NumberProgressBar 為okGo中的view /** Copyright 2016 jeasonlzy(廖子堯)** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/ package com.test.view;import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.view.View;import com.test.R;/*** ================================================* 作 者:jeasonlzy(廖子堯)Github地址:https://github.com/jeasonlzy* 版 本:1.0* 創(chuàng)建日期:16/9/11* 描 述:* 修訂歷史:* ================================================*/ public class NumberProgressBar extends View {public interface OnProgressBarListener {void onProgressChange(int current, int max);}private int mMaxProgress = 100;/*** Current progress, can not exceed the max progress.*/private int mCurrentProgress = 0;/*** The progress area bar color.*/private int mReachedBarColor;/*** The bar unreached area color.*/private int mUnreachedBarColor;/*** The progress text color.*/private int mTextColor;/*** The progress text size.*/private float mTextSize;/*** The height of the reached area.*/private float mReachedBarHeight;/*** The height of the unreached area.*/private float mUnreachedBarHeight;/*** The suffix of the number.*/private String mSuffix = "%";/*** The prefix.*/private String mPrefix = "";private final int default_text_color = Color.rgb(66, 145, 241);private final int default_reached_color = Color.rgb(66, 145, 241);private final int default_unreached_color = Color.rgb(204, 204, 204);private final float default_progress_text_offset;private final float default_text_size;private final float default_reached_bar_height;private final float default_unreached_bar_height;/*** For save and restore instance of progressbar.*/private static final String INSTANCE_STATE = "saved_instance";private static final String INSTANCE_TEXT_COLOR = "text_color";private static final String INSTANCE_TEXT_SIZE = "text_size";private static final String INSTANCE_REACHED_BAR_HEIGHT = "reached_bar_height";private static final String INSTANCE_REACHED_BAR_COLOR = "reached_bar_color";private static final String INSTANCE_UNREACHED_BAR_HEIGHT = "unreached_bar_height";private static final String INSTANCE_UNREACHED_BAR_COLOR = "unreached_bar_color";private static final String INSTANCE_MAX = "max";private static final String INSTANCE_PROGRESS = "progress";private static final String INSTANCE_SUFFIX = "suffix";private static final String INSTANCE_PREFIX = "prefix";private static final String INSTANCE_TEXT_VISIBILITY = "text_visibility";private static final int PROGRESS_TEXT_VISIBLE = 0;/*** The width of the text that to be drawn.*/private float mDrawTextWidth;/*** The drawn text start.*/private float mDrawTextStart;/*** The drawn text end.*/private float mDrawTextEnd;/*** The text that to be drawn in onDraw().*/private String mCurrentDrawText;/*** The Paint of the reached area.*/private Paint mReachedBarPaint;/*** The Paint of the unreached area.*/private Paint mUnreachedBarPaint;/*** The Paint of the progress text.*/private Paint mTextPaint;/*** Unreached bar area to draw rect.*/private RectF mUnreachedRectF = new RectF(0, 0, 0, 0);/*** Reached bar area rect.*/private RectF mReachedRectF = new RectF(0, 0, 0, 0);/*** The progress text offset.*/private float mOffset;/*** Determine if need to draw unreached area.*/private boolean mDrawUnreachedBar = true;private boolean mDrawReachedBar = true;private boolean mIfDrawText = true;/*** Listener*/private OnProgressBarListener mListener;public enum ProgressTextVisibility {Visible, Invisible}public NumberProgressBar(Context context) {this(context, null);}public NumberProgressBar(Context context, AttributeSet attrs) {this(context, attrs, 0);}public NumberProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);default_reached_bar_height = dp2px(1.5f);default_unreached_bar_height = dp2px(1.0f);default_text_size = sp2px(10);default_progress_text_offset = dp2px(3.0f);//load styled attributes.final TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.NumberProgressBar, defStyleAttr, 0);mReachedBarColor = attributes.getColor(R.styleable.NumberProgressBar_progress_reached_color, default_reached_color);mUnreachedBarColor = attributes.getColor(R.styleable.NumberProgressBar_progress_unreached_color, default_unreached_color);mTextColor = attributes.getColor(R.styleable.NumberProgressBar_progress_text_color, default_text_color);mTextSize = attributes.getDimension(R.styleable.NumberProgressBar_progress_text_size, default_text_size);mReachedBarHeight = attributes.getDimension(R.styleable.NumberProgressBar_progress_reached_bar_height, default_reached_bar_height);mUnreachedBarHeight = attributes.getDimension(R.styleable.NumberProgressBar_progress_unreached_bar_height, default_unreached_bar_height);mOffset = attributes.getDimension(R.styleable.NumberProgressBar_progress_text_offset, default_progress_text_offset);int textVisible = attributes.getInt(R.styleable.NumberProgressBar_progress_text_visibility, PROGRESS_TEXT_VISIBLE);if (textVisible != PROGRESS_TEXT_VISIBLE) {mIfDrawText = false;}setProgress(attributes.getInt(R.styleable.NumberProgressBar_progress_current, 0));setMax(attributes.getInt(R.styleable.NumberProgressBar_progress_max, 100));attributes.recycle();initializePainters();}@Overrideprotected int getSuggestedMinimumWidth() {return (int) mTextSize;}@Overrideprotected int getSuggestedMinimumHeight() {return Math.max((int) mTextSize, Math.max((int) mReachedBarHeight, (int) mUnreachedBarHeight));}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {setMeasuredDimension(measure(widthMeasureSpec, true), measure(heightMeasureSpec, false));}private int measure(int measureSpec, boolean isWidth) {int result;int mode = MeasureSpec.getMode(measureSpec);int size = MeasureSpec.getSize(measureSpec);int padding = isWidth ? getPaddingLeft() + getPaddingRight() : getPaddingTop() + getPaddingBottom();if (mode == MeasureSpec.EXACTLY) {result = size;} else {result = isWidth ? getSuggestedMinimumWidth() : getSuggestedMinimumHeight();result += padding;if (mode == MeasureSpec.AT_MOST) {if (isWidth) {result = Math.max(result, size);} else {result = Math.min(result, size);}}}return result;}@Overrideprotected void onDraw(Canvas canvas) {if (mIfDrawText) {calculateDrawRectF();} else {calculateDrawRectFWithoutProgressText();}if (mDrawReachedBar) {canvas.drawRect(mReachedRectF, mReachedBarPaint);}if (mDrawUnreachedBar) {canvas.drawRect(mUnreachedRectF, mUnreachedBarPaint);}if (mIfDrawText) canvas.drawText(mCurrentDrawText, mDrawTextStart, mDrawTextEnd, mTextPaint);}private void initializePainters() {mReachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);mReachedBarPaint.setColor(mReachedBarColor);mUnreachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);mUnreachedBarPaint.setColor(mUnreachedBarColor);mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);mTextPaint.setColor(mTextColor);mTextPaint.setTextSize(mTextSize);}private void calculateDrawRectFWithoutProgressText() {mReachedRectF.left = getPaddingLeft();mReachedRectF.top = getHeight() / 2.0f - mReachedBarHeight / 2.0f;mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight()) / (getMax() * 1.0f) * getProgress() + getPaddingLeft();mReachedRectF.bottom = getHeight() / 2.0f + mReachedBarHeight / 2.0f;mUnreachedRectF.left = mReachedRectF.right;mUnreachedRectF.right = getWidth() - getPaddingRight();mUnreachedRectF.top = getHeight() / 2.0f + -mUnreachedBarHeight / 2.0f;mUnreachedRectF.bottom = getHeight() / 2.0f + mUnreachedBarHeight / 2.0f;}private void calculateDrawRectF() {mCurrentDrawText = String.format("%d", getProgress() * 100 / getMax());mCurrentDrawText = mPrefix + mCurrentDrawText + mSuffix;mDrawTextWidth = mTextPaint.measureText(mCurrentDrawText);if (getProgress() == 0) {mDrawReachedBar = false;mDrawTextStart = getPaddingLeft();} else {mDrawReachedBar = true;mReachedRectF.left = getPaddingLeft();mReachedRectF.top = getHeight() / 2.0f - mReachedBarHeight / 2.0f;mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight()) / (getMax() * 1.0f) * getProgress() - mOffset + getPaddingLeft();mReachedRectF.bottom = getHeight() / 2.0f + mReachedBarHeight / 2.0f;mDrawTextStart = (mReachedRectF.right + mOffset);}mDrawTextEnd = (int) ((getHeight() / 2.0f) - ((mTextPaint.descent() + mTextPaint.ascent()) / 2.0f));if ((mDrawTextStart + mDrawTextWidth) >= getWidth() - getPaddingRight()) {mDrawTextStart = getWidth() - getPaddingRight() - mDrawTextWidth;mReachedRectF.right = mDrawTextStart - mOffset;}float unreachedBarStart = mDrawTextStart + mDrawTextWidth + mOffset;if (unreachedBarStart >= getWidth() - getPaddingRight()) {mDrawUnreachedBar = false;} else {mDrawUnreachedBar = true;mUnreachedRectF.left = unreachedBarStart;mUnreachedRectF.right = getWidth() - getPaddingRight();mUnreachedRectF.top = getHeight() / 2.0f + -mUnreachedBarHeight / 2.0f;mUnreachedRectF.bottom = getHeight() / 2.0f + mUnreachedBarHeight / 2.0f;}}/*** Get progress text color.** @return progress text color.*/public int getTextColor() {return mTextColor;}/*** Get progress text size.** @return progress text size.*/public float getProgressTextSize() {return mTextSize;}public int getUnreachedBarColor() {return mUnreachedBarColor;}public int getReachedBarColor() {return mReachedBarColor;}public int getProgress() {return mCurrentProgress;}public int getMax() {return mMaxProgress;}public float getReachedBarHeight() {return mReachedBarHeight;}public float getUnreachedBarHeight() {return mUnreachedBarHeight;}public void setProgressTextSize(float textSize) {this.mTextSize = textSize;mTextPaint.setTextSize(mTextSize);invalidate();}public void setProgressTextColor(int textColor) {this.mTextColor = textColor;mTextPaint.setColor(mTextColor);invalidate();}public void setUnreachedBarColor(int barColor) {this.mUnreachedBarColor = barColor;mUnreachedBarPaint.setColor(mUnreachedBarColor);invalidate();}public void setReachedBarColor(int progressColor) {this.mReachedBarColor = progressColor;mReachedBarPaint.setColor(mReachedBarColor);invalidate();}public void setReachedBarHeight(float height) {mReachedBarHeight = height;}public void setUnreachedBarHeight(float height) {mUnreachedBarHeight = height;}public void setMax(int maxProgress) {if (maxProgress > 0) {this.mMaxProgress = maxProgress;invalidate();}}public void setSuffix(String suffix) {if (suffix == null) {mSuffix = "";} else {mSuffix = suffix;}}public String getSuffix() {return mSuffix;}public void setPrefix(String prefix) {if (prefix == null) mPrefix = "";else {mPrefix = prefix;}}public String getPrefix() {return mPrefix;}public void incrementProgressBy(int by) {if (by > 0) {setProgress(getProgress() + by);}if (mListener != null) {mListener.onProgressChange(getProgress(), getMax());}}public void setProgress(int progress) {if (progress <= getMax() && progress >= 0) {this.mCurrentProgress = progress;invalidate();}}@Overrideprotected Parcelable onSaveInstanceState() {final Bundle bundle = new Bundle();bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());bundle.putInt(INSTANCE_TEXT_COLOR, getTextColor());bundle.putFloat(INSTANCE_TEXT_SIZE, getProgressTextSize());bundle.putFloat(INSTANCE_REACHED_BAR_HEIGHT, getReachedBarHeight());bundle.putFloat(INSTANCE_UNREACHED_BAR_HEIGHT, getUnreachedBarHeight());bundle.putInt(INSTANCE_REACHED_BAR_COLOR, getReachedBarColor());bundle.putInt(INSTANCE_UNREACHED_BAR_COLOR, getUnreachedBarColor());bundle.putInt(INSTANCE_MAX, getMax());bundle.putInt(INSTANCE_PROGRESS, getProgress());bundle.putString(INSTANCE_SUFFIX, getSuffix());bundle.putString(INSTANCE_PREFIX, getPrefix());bundle.putBoolean(INSTANCE_TEXT_VISIBILITY, getProgressTextVisibility());return bundle;}@Overrideprotected void onRestoreInstanceState(Parcelable state) {if (state instanceof Bundle) {final Bundle bundle = (Bundle) state;mTextColor = bundle.getInt(INSTANCE_TEXT_COLOR);mTextSize = bundle.getFloat(INSTANCE_TEXT_SIZE);mReachedBarHeight = bundle.getFloat(INSTANCE_REACHED_BAR_HEIGHT);mUnreachedBarHeight = bundle.getFloat(INSTANCE_UNREACHED_BAR_HEIGHT);mReachedBarColor = bundle.getInt(INSTANCE_REACHED_BAR_COLOR);mUnreachedBarColor = bundle.getInt(INSTANCE_UNREACHED_BAR_COLOR);initializePainters();setMax(bundle.getInt(INSTANCE_MAX));setProgress(bundle.getInt(INSTANCE_PROGRESS));setPrefix(bundle.getString(INSTANCE_PREFIX));setSuffix(bundle.getString(INSTANCE_SUFFIX));setProgressTextVisibility(bundle.getBoolean(INSTANCE_TEXT_VISIBILITY) ? ProgressTextVisibility.Visible : ProgressTextVisibility.Invisible);super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE));return;}super.onRestoreInstanceState(state);}public float dp2px(float dp) {final float scale = getResources().getDisplayMetrics().density;return dp * scale + 0.5f;}public float sp2px(float sp) {final float scale = getResources().getDisplayMetrics().scaledDensity;return sp * scale;}public void setProgressTextVisibility(ProgressTextVisibility visibility) {mIfDrawText = visibility == ProgressTextVisibility.Visible;invalidate();}public boolean getProgressTextVisibility() {return mIfDrawText;}public void setOnProgressBarListener(OnProgressBarListener listener) {mListener = listener;} }?
?
轉(zhuǎn)載于:https://www.cnblogs.com/cralor/p/9531616.html
總結(jié)
以上是生活随笔為你收集整理的Android 6.0 7.0 8.0 一个简单的app内更新版本-okgo app版本更新的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大白话看懂区块链
- 下一篇: 开机自动启动bios怎么设置时间 如何设