Skip to content

Commit

Permalink
优化
Browse files Browse the repository at this point in the history
  • Loading branch information
heyongrui committed Apr 22, 2020
1 parent f73851d commit 388c839
Show file tree
Hide file tree
Showing 16 changed files with 604 additions and 64 deletions.
31 changes: 21 additions & 10 deletions base/src/main/java/com/heyongrui/base/utils/UiUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
Expand Down Expand Up @@ -292,19 +293,29 @@ public static void setOnclickFeedBack(@ColorInt int normalColor, @ColorInt int p
}
}

private static long lastClickTime;//标识最后一次点击的时间
private static long[] mHits = new long[2];
private static String mLastMark;

/**
* 是否可以执行点击事件(防止按钮多次点击导致事件重复的方法判断)
* 每两次点击时间间隔在一定范围{@intervals}内,且点击达到指定次数{@clickCount}视为一次有效点击(适用于频繁点击只响应一次事件或者特殊需求)
*
* @return true-此次为有效点击 false-此次为无效点击
*/
public static boolean isPerformClickEvent() {
boolean flag = false;
long curClickTime = System.currentTimeMillis();
if ((curClickTime - lastClickTime) >= 1000) {
//两次点击按钮之间的点击间隔不能少于1000毫秒
flag = true;
public static boolean isMultipleClickValid(int clickCount, long intervals) {
StackTraceElement ste = new Throwable().getStackTrace()[1];
String key = ste.getFileName() + ste.getLineNumber();

if (!TextUtils.equals(mLastMark, key)) {
mHits = new long[clickCount];
}
mLastMark = key;

System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
mHits[mHits.length - 1] = SystemClock.uptimeMillis();

if ((mHits[mHits.length - 1] - mHits[0] <= intervals)) {
return true;
}
lastClickTime = curClickTime;
return flag;
return false;
}
}
83 changes: 53 additions & 30 deletions base/src/main/java/com/heyongrui/base/utils/UpdateCheckUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,24 @@
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.CacheControl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UpdateCheckUtil {

private final String TAG = "UpdateCheckUtil";
public static final int REQUEST_CODE_APP_INSTALL = 1000;

private AppCompatActivity mActivity;
private CompositeDisposable mCompositeDisposable;

private NotificationManager notificationManager;
private NotificationCompat.Builder builder;
private ProgressDialog progressDialog;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
private ProgressDialog mProgressDialog;
private boolean mIsDownLoadSucess;
private int NOTIFY_ID = 0x3;

public UpdateCheckUtil(AppCompatActivity activity) {
mActivity = activity;
Expand Down Expand Up @@ -179,12 +184,14 @@ public void onNo(Dialog dialog) {
}

private void startDownload(@NonNull String downloadUrl, @NonNull String authority, @NonNull String appName) {
mIsDownLoadSucess = false;
initNotification();
mCompositeDisposable.add(Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
InputStream inputStream = null;
OutputStream outputStream = null;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(downloadUrl).build();
CacheControl cc = new CacheControl.Builder().noStore().build();
Request request = new Request.Builder().cacheControl(cc).url(downloadUrl).build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Expand All @@ -204,14 +211,15 @@ private void startDownload(@NonNull String downloadUrl, @NonNull String authorit
if (progress != progress2) {
progress2 = progress;
// emitter.onNext(progress2);
builder.setProgress(100, progress2, false);
builder.setContentText(mActivity.getString(R.string.download_progress, progress2));
mBuilder.setProgress(100, progress2, false);
mBuilder.setContentText(mActivity.getString(R.string.download_progress, progress2));
if (progress2 == 100) {
builder.setContentInfo(mActivity.getString(R.string.download_done))
mIsDownLoadSucess = true;
mBuilder.setContentInfo(mActivity.getString(R.string.download_done))
.setContentTitle(mActivity.getString(R.string.download_done));
}
notificationManager.notify(0x3, builder.build());
progressDialog.setProgress(progress2);
mNotificationManager.notify(NOTIFY_ID, mBuilder.build());
mProgressDialog.setProgress(progress2);
Log.v("startDownload: ", progress2 + "%");
}
outputStream.write(data, 0, count);
Expand Down Expand Up @@ -242,52 +250,67 @@ private void startDownload(@NonNull String downloadUrl, @NonNull String authorit
//更新通知栏的下载进度
}, throwable -> {//onError
cancelTask();
ToastUtils.showShort(R.string.update_error);
}, () -> {//onComplete
progressDialog.dismiss();
installApp(mActivity, authority, appName);
cancelNotifyAndDialog();
if (mIsDownLoadSucess) {
installApp(mActivity, authority, appName);
} else {
ToastUtils.showShort(R.string.update_error);
}
}));
}

private void initNotification() {
//初始化通知栏
String channelId = "channell_id1";
String channelName = "下载通知";
if (notificationManager == null) {
notificationManager = (NotificationManager) mActivity.getSystemService(Activity.NOTIFICATION_SERVICE);
if (mNotificationManager == null) {
mNotificationManager = (NotificationManager) mActivity.getSystemService(Activity.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT));
mNotificationManager.createNotificationChannel(new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW));
}
}
if (builder == null) {
builder = new NotificationCompat.Builder(mActivity, channelId);
if (mBuilder == null) {
mBuilder = new NotificationCompat.Builder(mActivity, channelId);
}
//设置通知栏属性
builder.setSmallIcon(R.drawable.ic_launcher)
mBuilder.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setOngoing(false)
.setContentInfo(mActivity.getString(R.string.downloading))
.setContentTitle(mActivity.getString(R.string.doing_download));
//初始化下载进度条弹窗
if (progressDialog == null) {
progressDialog = new ProgressDialog(mActivity);
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(mActivity);
}
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
progressDialog.setCancelable(false);// 设置是否可以通过点击Back键取消
progressDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
progressDialog.setTitle(R.string.downloading);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.setOnCancelListener(dialogInterface -> cancelTask());
progressDialog.show();
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
mProgressDialog.setCancelable(false);// 设置是否可以通过点击Back键取消
mProgressDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
mProgressDialog.setTitle(R.string.downloading);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(0);
mProgressDialog.setOnCancelListener(dialogInterface -> cancelTask());
mProgressDialog.show();
}

public void cancelTask() {
//取消任务
cancelDisposable();
cancelNotifyAndDialog();
}

private void cancelDisposable() {
if (mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
mCompositeDisposable.clear();
}
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}

private void cancelNotifyAndDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
if (null != mNotificationManager) {
mNotificationManager.cancel(NOTIFY_ID);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,12 @@ public Observable<KaiYanDto> getRelatedRecommend(int id) {
.getRelatedRecommend(id)
.compose(RxHelper.rxSchedulerHelper());
}

// public Flowable<Optional<KaiYanDto>> contractExpire(int id) {
// return ApiService.createApi(KaiYanApi.class, "", CustomConverterFactory.create())
// .getRelatedRecommend(id)
// .compose(RxHelper.rxSchedulerHelperFlowable())
// .compose(RxHelper.rxHandleResultFlowableNullable());
// }

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.heyongrui.network.convert.CustomIOException;
import com.heyongrui.network.core.CoreApiException;
import com.heyongrui.network.core.CoreHeader;

import org.json.JSONException;
import org.json.JSONObject;
Expand Down Expand Up @@ -53,8 +55,8 @@ public static CoreApiException analysisExcetpion(Throwable e) {
try {
String errorBody = ((HttpException) e).response().errorBody().string();
JSONObject jsonObject = new JSONObject(errorBody);
int status = jsonObject.getInt("status");
String info = jsonObject.getString("info");
int status = jsonObject.getInt(CoreHeader.KEY_STATUS);
String info = jsonObject.getString(CoreHeader.KEY_MSG);
apiException = new CoreApiException(status, info);
} catch (IOException ex) {
ex.printStackTrace();
Expand All @@ -63,6 +65,8 @@ public static CoreApiException analysisExcetpion(Throwable e) {
ex.printStackTrace();
apiException = new CoreApiException(e, TIMEOUT_ERROR, "解析错误");
}
} else if (e instanceof CustomIOException) {
apiException = new CoreApiException(e.getCause(), ((CustomIOException) e).getErrorCode(), ((CustomIOException) e).getMsg());
} else if (e instanceof UnknownHostException) {
//主机挂了,也就是你服务器关了
apiException = new CoreApiException(e, UNKOWNHOST_ERROR, "服务异常");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

/**
* Created by lambert on 2018/10/23.
* 适用于Observable
*/

public abstract class ResponseDisposable<T> extends DisposableObserver<T> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package com.heyongrui.network.configure;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.heyongrui.base.widget.catloadingview.CatLoadingDialog;
import com.heyongrui.network.core.CoreApiException;

import java.lang.ref.SoftReference;

import io.reactivex.subscribers.DisposableSubscriber;


/**
* Created by lambert on 2018/10/23.
* 适用于Flowable
*/
public abstract class ResponseSubscriber<T> extends DisposableSubscriber<T> {

private SoftReference<Context> mContext;
private Dialog mLoadingDialog;

//调用此无参构造函数无网络加载框
public ResponseSubscriber(Context context) {
this(context, false);
}

public ResponseSubscriber(Context context, boolean isShowLoading) {
this(context, isShowLoading, null);
}

public ResponseSubscriber(Context context, boolean isShowLoading, String loadingContent) {
if (context != null) {
mContext = new SoftReference(context);
if (isShowLoading) {
loadingContent = TextUtils.isEmpty(loadingContent) ? "" : loadingContent;
showDialog(loadingContent);
}
}
}

@Override
protected void onStart() {
super.onStart();
}

@Override
public void onNext(T t) {
dismissDialog();
onSuccess(t);
}

@Override
public void onError(Throwable e) {
unsubscribe();
dismissDialog();
//统一处理错误异常
CoreApiException coreApiException = FactoryException.analysisExcetpion(e);
//用户登录失效,清除本地用户信息
int code = coreApiException.getCode();
if (code == 1105) {
SPUtils spUtils = SPUtils.getInstance("http_request");
spUtils.put("http_request_auth_token", "");
}
//返回错误信息
onFailure(coreApiException.getCode(), coreApiException.getDisplayMessage());
}

@Override
public void onComplete() {
unsubscribe();
dismissDialog();
}

protected abstract void onSuccess(T t);

protected abstract void onFailure(int errorCode, String errorMsg);

private void showDialog(String loadingContent) {
if (mContext == null) return;
Context context = mContext.get();
if (context == null) return;
if (mLoadingDialog == null) {
mLoadingDialog = new CatLoadingDialog(context);
((CatLoadingDialog) mLoadingDialog).setGraduallyText(loadingContent);
}
mLoadingDialog.setCancelable(true);
mLoadingDialog.setCanceledOnTouchOutside(false);
mLoadingDialog.setOnCancelListener(dialog -> unsubscribe());
mLoadingDialog.setOnDismissListener(dialogInterface -> unsubscribe());
if (!mLoadingDialog.isShowing()) {
mLoadingDialog.show();
}
}

private void dismissDialog() {
if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
mLoadingDialog.dismiss();
}
}

public void unsubscribe() {
if (isDisposed()) {
dispose();
}
}

}
Loading

0 comments on commit 388c839

Please sign in to comment.