diff --git a/.gitignore b/.gitignore index 3ec053d928..f11e27d274 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,5 @@ /build /captures .externalNativeBuild -.cxx \ No newline at end of file +.cxx +.gitlab-ci.yml \ No newline at end of file diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index c4416b34c7..ab633b66ce 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -25,3 +25,19 @@ inspect java and kotlin codes: except: - master allow_failure: true + +sonarqube-check: + image: gradle:jre11-slim + variables: + SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar" # Defines the location of the analysis task cache + GIT_DEPTH: "0" # Tells git to fetch all the branches of the project, required by the analysis task + cache: + key: "${CI_JOB_NAME}" + paths: + - .sonar/cache + script: gradle sonarqube + allow_failure: true + only: + - merge_requests + - $CI_COMMIT_BRANCH + - pushes \ No newline at end of file diff --git a/OCH/bus/driver/src/jinlvvan/java/com/mogo/och/bus/model/OrderModel.java b/OCH/bus/driver/src/jinlvvan/java/com/mogo/och/bus/model/OrderModel.java index 0c12f4cad9..84d8af86be 100644 --- a/OCH/bus/driver/src/jinlvvan/java/com/mogo/och/bus/model/OrderModel.java +++ b/OCH/bus/driver/src/jinlvvan/java/com/mogo/och/bus/model/OrderModel.java @@ -7,7 +7,6 @@ import static com.mogo.och.bus.constant.BusConst.STATION_STATUS_STOPPED; import android.content.Context; import android.os.Handler; -import android.os.Message; import android.text.TextUtils; import androidx.annotation.NonNull; @@ -81,7 +80,6 @@ import java.util.ArrayList; import java.util.List; import io.reactivex.exceptions.UndeliverableException; -import io.reactivex.functions.Consumer; import io.reactivex.plugins.RxJavaPlugins; import mogo.telematics.pad.MessagePad; @@ -98,6 +96,7 @@ public class OrderModel { private int backgroundCurrentStationIndex = 0;//A->B 此处值是A站点索引 private static volatile OrderModel sInstance; + private static final byte[] obj = new byte[0]; private Context mContext; private final List stationList = new ArrayList<>(); private BusRoutesResult busRoutesResult = null; @@ -125,20 +124,20 @@ public class OrderModel { private LoginService loginService; - private final Handler handler = new Handler(new Handler.Callback() { - @Override - public boolean handleMessage(Message msg) { - if (msg.what == MSG_QUERY_BUS_STATION) { - queryBusRoutes(); - return true; - } - return false; + private final Handler handler = new Handler(msg -> { + if (msg.what == MSG_QUERY_BUS_STATION) { + queryBusRoutes(); + return true; } + return false; }); + private OrderModel() { + } + public static OrderModel getInstance() { if (sInstance == null) { - synchronized (OrderModel.class) { + synchronized (obj) { if (sInstance == null) { sInstance = new OrderModel(); } @@ -147,10 +146,6 @@ public class OrderModel { return sInstance; } - private OrderModel() { - - } - public void init() { mContext = AbsMogoApplication.getApp(); loginService = (LoginService) ARouter.getInstance().build(OchCommonConst.LOGINSERVICE).navigation(); @@ -171,7 +166,7 @@ public class OrderModel { OCHSocketMessageManager.INSTANCE.registerSocketMessageListener(//监听核销乘客 OCHSocketMessageManager.msgWriteOffPassengerType, - mWriteOffPassengeOnMessageListener); + mWriteOffPassengerOnMessageListener); AbnormalFactorsLoopManager.INSTANCE.startLoopAbnormalFactors(mContext); @@ -180,38 +175,35 @@ public class OrderModel { //2022.1.28 // 调用Disposable.dispose() 时候会出现InterruptedException 导致出现崩溃 // The exception could not be delivered to the consumer because it has already canceled/disposed - // the flow or the excTeption has nowhere to go to begin with - RxJavaPlugins.setErrorHandler(new Consumer() { - @Override - public void accept(Throwable e) { - if (e instanceof UndeliverableException) { - e = e.getCause(); - CallerLogger.d(M_BUS + TAG, "UndeliverableException"); - } - if ((e instanceof IOException)) {// - // fine, irrelevant network problem or API that throws on cancellation - CallerLogger.d(M_BUS + TAG, "IOException"); - return; - } - if (e instanceof InterruptedException) { - // fine, some blocking code was interrupted by a dispose call - CallerLogger.d(M_BUS + TAG, "InterruptedException"); - return; - } - if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { - // that's likely a bug in the application - CallerLogger.d(M_BUS + TAG, "NullPointerException or IllegalArgumentException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - if (e instanceof IllegalStateException) { - // that's a bug in RxJava or in a custom operator - CallerLogger.d(M_BUS + TAG, "IllegalStateException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - CallerLogger.d(M_BUS + TAG, "Undeliverable exception"); + // the flow or the exception has nowhere to go to begin with + RxJavaPlugins.setErrorHandler(e -> { + if (e instanceof UndeliverableException) { + e = e.getCause(); + CallerLogger.d(M_BUS + TAG, "UndeliverableException"); } + if ((e instanceof IOException)) { + // fine, irrelevant network problem or API that throws on cancellation + CallerLogger.d(M_BUS + TAG, "IOException"); + return; + } + if (e instanceof InterruptedException) { + // fine, some blocking code was interrupted by a dispose call + CallerLogger.d(M_BUS + TAG, "InterruptedException"); + return; + } + if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { + // that's likely a bug in the application + CallerLogger.d(M_BUS + TAG, "NullPointerException or IllegalArgumentException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + if (e instanceof IllegalStateException) { + // that's a bug in RxJava or in a custom operator + CallerLogger.d(M_BUS + TAG, "IllegalStateException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + CallerLogger.d(M_BUS + TAG, "Undeliverable exception"); }); } @@ -234,7 +226,7 @@ public class OrderModel { } }; - private final IMogoOnMessageListener mWriteOffPassengeOnMessageListener = + private final IMogoOnMessageListener mWriteOffPassengerOnMessageListener = new IMogoOnMessageListener() { @Override public Class target() { @@ -272,11 +264,8 @@ public class OrderModel { this.mControllerStatusCallback = callback; } - private final ITrajectoryListener trajectoryListener = new ITrajectoryListener() { - @Override - public void trajectoryCallback(@NonNull List routeArrivied, @NonNull List routeArriving, @NonNull MogoLocation location) { + private final ITrajectoryListener trajectoryListener = (routeArrivied, routeArriving, location) -> { - } }; private final IMoGoPlanningRottingListener moGoAutopilotPlanningListener = new IMoGoPlanningRottingListener() { @@ -361,11 +350,6 @@ public class OrderModel { TrajectoryAndDistanceManager.INSTANCE.removeListener(TAG); } - private Object readResolve() { - // 阻止反序列化,必须实现 Serializable 接口 - return sInstance; - } - private final IMogoStatusChangedListener mMogoStatusChangedListener = new IMogoStatusChangedListener() { // VR mode变更回调 @Override @@ -444,8 +428,6 @@ public class OrderModel { CallerLogger.d(M_BUS + TAG, "judgeArrivedStation() = 刚过站且在15m内"); onArriveAt(null); //无自动驾驶到站信息传null } - - return; } } @@ -621,10 +603,7 @@ public class OrderModel { leaveTTSTips(nextStation,nextStationKr); if (busRoutesResult != null) { - boolean isLastStop = false; - if (leaveIndex + 1 == stationList.size() - 1) { - isLastStop = true; - } + boolean isLastStop = leaveIndex + 1 == stationList.size() - 1; //给bus外屏发送 BusSendTripInfoManager.INSTANCE.sendBusTripInfo(BusSendTripInfoManager.LEAVE_STATION , busRoutesResult.getName() @@ -768,10 +747,7 @@ public class OrderModel { private void arriveStationSuccess(int arrivedStationIndex, String departureStopName, String arriveStation, String arriveStationKr) { if (busRoutesResult != null) { - boolean isLastStop = false; - if (arrivedStationIndex == busRoutesResult.getSites().size() - 1) { - isLastStop = true; - } + boolean isLastStop = arrivedStationIndex == busRoutesResult.getSites().size() - 1; //给bus外屏发送 BusSendTripInfoManager.INSTANCE.sendBusTripInfo(BusSendTripInfoManager.ARRIVE_STATION , busRoutesResult.getName() @@ -845,12 +821,7 @@ public class OrderModel { //车站10s后播报 private void leaveTTSTips(String nextStation,String nextStationKr) { - UiThreadHandler.postDelayed(new Runnable() { - @Override - public void run() { - VoiceManager.INSTANCE.leaveStationBus(nextStation,nextStationKr); - } - },DELAY_10S); + UiThreadHandler.postDelayed(() -> VoiceManager.INSTANCE.leaveStationBus(nextStation,nextStationKr),DELAY_10S); } /** @@ -981,16 +952,12 @@ public class OrderModel { } } - Runnable tip3Runnable = new Runnable() { - @Override - public void run() { - - if (backgroundCurrentStationIndex == 0 && stationList.get(0).getDrivingStatus() == STATION_STATUS_STOPPED - && !stationList.get(0).isLeaving()){ - tipStartTask("3"); - }else { - removeTipRunnables(); - } + Runnable tip3Runnable = () -> { + if (backgroundCurrentStationIndex == 0 && stationList.get(0).getDrivingStatus() == STATION_STATUS_STOPPED + && !stationList.get(0).isLeaving()){ + tipStartTask("3"); + }else { + removeTipRunnables(); } }; @@ -1005,16 +972,11 @@ public class OrderModel { VoiceNotice.showNotice(tips); } - Runnable tip1Runnable = new Runnable() { - @Override - public void run() { - if (backgroundCurrentStationIndex == 0 && stationList != null && - stationList.get(0).getDrivingStatus() == STATION_STATUS_STOPPED - && !stationList.get(0).isLeaving()){ - tipStartTask("1"); - }else { - removeTipRunnables(); - } + Runnable tip1Runnable = () -> { + if (backgroundCurrentStationIndex == 0 && stationList.get(0).getDrivingStatus() == STATION_STATUS_STOPPED && !stationList.get(0).isLeaving()){ + tipStartTask("1"); + }else { + removeTipRunnables(); } }; @@ -1205,7 +1167,7 @@ public class OrderModel { } public void triggerStartServiceEvent(boolean isRestart, boolean send) { - if (stationList == null || backgroundCurrentStationIndex >= stationList.size() - 1) { + if (backgroundCurrentStationIndex >= stationList.size() - 1) { return; } BusStationBean currentStation = stationList.get(backgroundCurrentStationIndex); @@ -1215,7 +1177,7 @@ public class OrderModel { } public void triggerUnableStartAPReasonEvent() { - if (stationList == null || backgroundCurrentStationIndex >= stationList.size() - 1) { + if (backgroundCurrentStationIndex >= stationList.size() - 1) { return; } BusStationBean currentStation = stationList.get(backgroundCurrentStationIndex); @@ -1253,8 +1215,8 @@ public class OrderModel { } private AutopilotControlParameters initAutopilotControlParameters(int leaveIndex) { - BusStationBean currentStation = null; - BusStationBean nextStation = null; + BusStationBean currentStation; + BusStationBean nextStation; if (leaveIndex < 0) { if (backgroundCurrentStationIndex + 1 > stationList.size() - 1 || !isGoingToNextStation) { diff --git a/OCH/bus/driver/src/main/java/com/mogo/och/bus/bean/BusRoutesResult.java b/OCH/bus/driver/src/main/java/com/mogo/och/bus/bean/BusRoutesResult.java index 4b652d30df..66b7189524 100644 --- a/OCH/bus/driver/src/main/java/com/mogo/och/bus/bean/BusRoutesResult.java +++ b/OCH/bus/driver/src/main/java/com/mogo/och/bus/bean/BusRoutesResult.java @@ -46,7 +46,7 @@ public class BusRoutesResult { return sites; } - public void setSite(List site) { + public void setSites(List sites) { this.sites = sites; } diff --git a/OCH/bus/driver/src/main/java/com/mogo/och/bus/model/BusLineModel.java b/OCH/bus/driver/src/main/java/com/mogo/och/bus/model/BusLineModel.java index b116e97940..9ab9e562f7 100644 --- a/OCH/bus/driver/src/main/java/com/mogo/och/bus/model/BusLineModel.java +++ b/OCH/bus/driver/src/main/java/com/mogo/och/bus/model/BusLineModel.java @@ -1,7 +1,6 @@ package com.mogo.och.bus.model; import android.content.Context; -import android.util.Log; import com.mogo.commons.AbsMogoApplication; import com.mogo.eagle.core.utilcode.util.NetworkUtils; @@ -24,9 +23,13 @@ public class BusLineModel { private static volatile BusLineModel sInstance; private Context mContext; private IBusLinesCallback mBusLinesCallback; + private static final byte[] obj = new byte[0]; + + private BusLineModel() { + } public static BusLineModel getInstance() { if ( sInstance == null ) { - synchronized ( BusLineModel.class ) { + synchronized ( obj ) { if ( sInstance == null ) { sInstance = new BusLineModel(); } @@ -34,9 +37,7 @@ public class BusLineModel { } return sInstance; } - private BusLineModel() { - } public void init() { mContext = AbsMogoApplication.getApp(); } @@ -79,7 +80,7 @@ public class BusLineModel { /** * 通过线路id 查询线路排班表 - * @param lineId + * @param lineId 线路id * @param position 位置 */ public void queryBusLineTasksById(int lineId, int position,boolean autoRefresh){ diff --git a/OCH/bus/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java b/OCH/bus/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java index 1571739e3b..15ff420cc1 100644 --- a/OCH/bus/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java +++ b/OCH/bus/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java @@ -11,7 +11,6 @@ import androidx.annotation.NonNull; import androidx.core.view.ViewCompat; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.RecyclerView; -import androidx.recyclerview.widget.SimpleItemAnimator; import java.util.ArrayList; import java.util.List; @@ -28,19 +27,19 @@ public class OpenItemAnimator extends DefaultItemAnimator { private static TimeInterpolator sDefaultInterpolator; - private ArrayList mPendingRemovals = new ArrayList<>(); - private ArrayList mPendingAdditions = new ArrayList<>(); - private ArrayList mPendingMoves = new ArrayList<>(); - private ArrayList mPendingChanges = new ArrayList<>(); + private final ArrayList mPendingRemovals = new ArrayList<>(); + private final ArrayList mPendingAdditions = new ArrayList<>(); + private final ArrayList mPendingMoves = new ArrayList<>(); + private final ArrayList mPendingChanges = new ArrayList<>(); - ArrayList> mAdditionsList = new ArrayList<>(); - ArrayList> mMovesList = new ArrayList<>(); - ArrayList> mChangesList = new ArrayList<>(); + private final ArrayList> mAdditionsList = new ArrayList<>(); + private final ArrayList> mMovesList = new ArrayList<>(); + private final ArrayList> mChangesList = new ArrayList<>(); - ArrayList mAddAnimations = new ArrayList<>(); - ArrayList mMoveAnimations = new ArrayList<>(); - ArrayList mRemoveAnimations = new ArrayList<>(); - ArrayList mChangeAnimations = new ArrayList<>(); + private final ArrayList mAddAnimations = new ArrayList<>(); + private final ArrayList mMoveAnimations = new ArrayList<>(); + private final ArrayList mRemoveAnimations = new ArrayList<>(); + private final ArrayList mChangeAnimations = new ArrayList<>(); private static class MoveInfo { public RecyclerView.ViewHolder holder; @@ -102,20 +101,16 @@ public class OpenItemAnimator extends DefaultItemAnimator { mPendingRemovals.clear(); // Next, move stuff if (movesPending) { - final ArrayList moves = new ArrayList<>(); - moves.addAll(mPendingMoves); + final ArrayList moves = new ArrayList<>(mPendingMoves); mMovesList.add(moves); mPendingMoves.clear(); - Runnable mover = new Runnable() { - @Override - public void run() { - for (MoveInfo moveInfo : moves) { - animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, - moveInfo.toX, moveInfo.toY); - } - moves.clear(); - mMovesList.remove(moves); + Runnable mover = () -> { + for (MoveInfo moveInfo : moves) { + animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, + moveInfo.toX, moveInfo.toY); } + moves.clear(); + mMovesList.remove(moves); }; if (removalsPending) { View view = moves.get(0).holder.itemView; @@ -126,19 +121,15 @@ public class OpenItemAnimator extends DefaultItemAnimator { } // Next, change stuff, to run in parallel with move animations if (changesPending) { - final ArrayList changes = new ArrayList<>(); - changes.addAll(mPendingChanges); + final ArrayList changes = new ArrayList<>(mPendingChanges); mChangesList.add(changes); mPendingChanges.clear(); - Runnable changer = new Runnable() { - @Override - public void run() { - for (ChangeInfo change : changes) { - animateChangeImpl(change); - } - changes.clear(); - mChangesList.remove(changes); + Runnable changer = () -> { + for (ChangeInfo change : changes) { + animateChangeImpl(change); } + changes.clear(); + mChangesList.remove(changes); }; if (removalsPending) { RecyclerView.ViewHolder holder = changes.get(0).oldHolder; @@ -149,19 +140,15 @@ public class OpenItemAnimator extends DefaultItemAnimator { } // Next, add stuff if (additionsPending) { - final ArrayList additions = new ArrayList<>(); - additions.addAll(mPendingAdditions); + final ArrayList additions = new ArrayList<>(mPendingAdditions); mAdditionsList.add(additions); mPendingAdditions.clear(); - Runnable adder = new Runnable() { - @Override - public void run() { - for (RecyclerView.ViewHolder holder : additions) { - animateAddImpl(holder); - } - additions.clear(); - mAdditionsList.remove(additions); + Runnable adder = () -> { + for (RecyclerView.ViewHolder holder : additions) { + animateAddImpl(holder); } + additions.clear(); + mAdditionsList.remove(additions); }; if (removalsPending || movesPending || changesPending) { long removeDuration = removalsPending ? getRemoveDuration() : 0; @@ -341,8 +328,8 @@ public class OpenItemAnimator extends DefaultItemAnimator { final ViewPropertyAnimator oldViewAnim = view.animate().setDuration( getChangeDuration()); mChangeAnimations.add(changeInfo.oldHolder); - oldViewAnim.translationX(changeInfo.toX - changeInfo.fromX); - oldViewAnim.translationY(changeInfo.toY - changeInfo.fromY); + oldViewAnim.translationX((float) (changeInfo.toX - changeInfo.fromX)); + oldViewAnim.translationY((float) (changeInfo.toY - changeInfo.fromY)); oldViewAnim.alpha(0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animator) { @@ -480,25 +467,25 @@ public class OpenItemAnimator extends DefaultItemAnimator { } // animations should be ended by the cancel above. - //noinspection PointlessBooleanExpression,ConstantConditions + //noinspection Pointless BooleanExpression,ConstantConditions if (mRemoveAnimations.remove(item) && DEBUG) { throw new IllegalStateException("after animation is cancelled, item should not be in " + "mRemoveAnimations list"); } - //noinspection PointlessBooleanExpression,ConstantConditions + //noinspection Pointless BooleanExpression,ConstantConditions if (mAddAnimations.remove(item) && DEBUG) { throw new IllegalStateException("after animation is cancelled, item should not be in " + "mAddAnimations list"); } - //noinspection PointlessBooleanExpression,ConstantConditions + //noinspection Pointless BooleanExpression,ConstantConditions if (mChangeAnimations.remove(item) && DEBUG) { throw new IllegalStateException("after animation is cancelled, item should not be in " + "mChangeAnimations list"); } - //noinspection PointlessBooleanExpression,ConstantConditions + //noinspection Pointless BooleanExpression,ConstantConditions if (mMoveAnimations.remove(item) && DEBUG) { throw new IllegalStateException("after animation is cancelled, item should not be in " + "mMoveAnimations list"); diff --git a/OCH/bus/driver/src/main/java/com/mogo/och/bus/view/BusArcView.java b/OCH/bus/driver/src/main/java/com/mogo/och/bus/view/BusArcView.java index a9e7bdff5d..29525b0169 100644 --- a/OCH/bus/driver/src/main/java/com/mogo/och/bus/view/BusArcView.java +++ b/OCH/bus/driver/src/main/java/com/mogo/och/bus/view/BusArcView.java @@ -24,13 +24,13 @@ import com.mogo.och.bus.R; public class BusArcView extends View { //中心的文字描述 - private String mDes = "KM/H"; + private final String mDes = "KM/H"; //根据数据显示的圆弧Paint private Paint mArcPaint; //圆弧颜色 private int mArcColor; //圆弧的画笔的宽度 - private float mStrokeWith = getResources().getDimension(R.dimen.bus_ext_arcView_stroke_with); + private final float mStrokeWith = getResources().getDimension(R.dimen.bus_ext_arcView_stroke_with); //文字描述的paint private Paint mTextPaint; @@ -39,9 +39,9 @@ public class BusArcView extends View { //当前数据 private int currentValue; //最大数据 - private int maxValue = 240; + private final int maxValue = 240; //圆弧背景的开始和结束间的夹角大小 - private float mAngle = 270; + private final float mAngle = 270; //上次绘制圆弧夹角 private float lastAngle = 0; @@ -75,13 +75,13 @@ public class BusArcView extends View { mTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); //绘制中心的数值 mTextPaint.getTextBounds(mValue, 0, mValue.length(), mRect); - canvas.drawText(mValue, getWidth() / 2, getHeight() / 2 + mRect.height() / 2 - 10, mTextPaint); + canvas.drawText(mValue, getWidth() / 2.0f, getHeight() / 2.0f + mRect.height() / 2.0f - 10, mTextPaint); mTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); //绘制中心文字描述 mTextPaint.setTextSize(getResources().getDimension(R.dimen.bus_ext_arcView_des_text_size)); mTextPaint.getTextBounds(mDes, 0, mDes.length(), mRect); - canvas.drawText(mDes, getWidth() / 2, getHeight() * 17 / 20 + mRect.height() / 2, mTextPaint); + canvas.drawText(mDes, getWidth() / 2.0f, getHeight() * 17.0f / 20.0f + mRect.height() / 2.0f, mTextPaint); } private void drawArc(Canvas canvas) { @@ -135,13 +135,10 @@ public class BusArcView extends View { ValueAnimator progressAnimator = ValueAnimator.ofFloat(startAngle, currentAngle); progressAnimator.setDuration(time); progressAnimator.setTarget(mIncludedAngle); - progressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { - @Override - public void onAnimationUpdate(ValueAnimator animation) { - mIncludedAngle = (float) animation.getAnimatedValue(); - //重新绘制,不然不会出现效果 - postInvalidate(); - } + progressAnimator.addUpdateListener(animation -> { + mIncludedAngle = (float) animation.getAnimatedValue(); + //重新绘制,不然不会出现效果 + postInvalidate(); }); //开始执行动画 progressAnimator.start(); diff --git a/OCH/bus/driver/src/main/java/com/mogo/och/bus/view/SlidePanelView.java b/OCH/bus/driver/src/main/java/com/mogo/och/bus/view/SlidePanelView.java index e010f37a76..7219b7b20d 100644 --- a/OCH/bus/driver/src/main/java/com/mogo/och/bus/view/SlidePanelView.java +++ b/OCH/bus/driver/src/main/java/com/mogo/och/bus/view/SlidePanelView.java @@ -22,7 +22,6 @@ import android.view.animation.DecelerateInterpolator; import androidx.annotation.Nullable; import com.mogo.commons.AbsMogoApplication; -import com.mogo.eagle.core.utilcode.util.BitmapHelper; import com.mogo.och.bus.R; import me.jessyan.autosize.AutoSizeConfig; @@ -93,7 +92,7 @@ public class SlidePanelView extends View { private ObjectAnimator matrixAnim; private String blockText = STRING_SLIDE_TO_RIGHT; - private Paint.FontMetrics blockTextMetrics = new Paint.FontMetrics(); + private final Paint.FontMetrics blockTextMetrics = new Paint.FontMetrics(); private static final int GRADIENT_OFFSET = 200; @@ -250,7 +249,7 @@ public class SlidePanelView extends View { private void startBlockBackAnim() { ObjectAnimator blockBackanimator = ObjectAnimator.ofInt(this, "blockOffset", blockOffset, 0); blockBackanimator.setInterpolator(new DecelerateInterpolator()); - blockBackanimator.setDuration(1000 * blockOffset / getWidth()); + blockBackanimator.setDuration(1000L * blockOffset / getWidth()); blockBackanimator.start(); lastX = 0; } @@ -259,15 +258,15 @@ public class SlidePanelView extends View { protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 画背景 - canvas.drawRoundRect(bgRectF, (float) getHeight() / 2, (float) getHeight() / 2, bgPaint); + canvas.drawRoundRect(bgRectF, (float) getHeight() / 2.0f, (float) getHeight() / 2.0f, bgPaint); // 画文字 gradientMatrix.setTranslate(matrixTranslate, 0); textGradient.setLocalMatrix(gradientMatrix); canvas.save(); - canvas.drawText(blockText, blockWidth + BLOCK_START_X + textMarginLeft, textOffset, textPaint); + canvas.drawText(blockText, (float) (blockWidth + BLOCK_START_X + textMarginLeft), textOffset, textPaint); canvas.restore(); // 画滑块 - canvas.drawBitmap(bmBlock, BLOCK_START_X + blockOffset, BLOCK_START_Y, blockPaint); + canvas.drawBitmap(bmBlock, (float) (BLOCK_START_X + blockOffset), (float) BLOCK_START_Y, blockPaint); } public interface OnSlidePanelMoveToEndListener { diff --git a/OCH/bus/passenger/build.gradle b/OCH/bus/passenger/build.gradle index 6732195e81..391d65936f 100644 --- a/OCH/bus/passenger/build.gradle +++ b/OCH/bus/passenger/build.gradle @@ -68,8 +68,9 @@ dependencies { implementation project(":OCH:mogo-och-common-module") compileOnly project(":libraries:mogo-map") implementation project(':core:mogo-core-res') - testImplementation 'junit:junit:4.12' + androidTestImplementation rootProject.ext.dependencies.androidxjunit + testImplementation rootProject.ext.dependencies.junit } apply from: new File(rootProject.rootDir, "gradle/upload.gradle").toString() \ No newline at end of file diff --git a/OCH/bus/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/MogoOCHBusPassenger.java b/OCH/bus/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/MogoOCHBusPassenger.java index 5d1778ca79..cf1643aa61 100644 --- a/OCH/bus/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/MogoOCHBusPassenger.java +++ b/OCH/bus/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/MogoOCHBusPassenger.java @@ -47,7 +47,7 @@ public class MogoOCHBusPassenger implements IMogoOCH { this.mContainerId = containerId; showFragment(); - if (AppIdentityModeUtils.isJL(FunctionBuildConfig.appIdentityMode)) { + if (AppIdentityModeUtils.isJL(FunctionBuildConfig.appIdentityMode) && activity != null) { MultiDisplayUtils.INSTANCE.startActWithSecond(activity, VideoPlayerActivity.class); } diff --git a/OCH/bus/passenger/src/main/java/com/mogo/och/bus/passenger/utils/BusPassengerMapAssetStyleUtil.java b/OCH/bus/passenger/src/main/java/com/mogo/och/bus/passenger/utils/BusPassengerMapAssetStyleUtil.java index edab28cb78..3cad825966 100644 --- a/OCH/bus/passenger/src/main/java/com/mogo/och/bus/passenger/utils/BusPassengerMapAssetStyleUtil.java +++ b/OCH/bus/passenger/src/main/java/com/mogo/och/bus/passenger/utils/BusPassengerMapAssetStyleUtil.java @@ -19,7 +19,10 @@ public class BusPassengerMapAssetStyleUtil { is1 = context.getResources().getAssets().open(fileName); //eg. over_view_style.data int lenght1 = is1.available(); buffer1 = new byte[lenght1]; - is1.read(buffer1); + int count = 0; + while ((count = is1.read(buffer1)) > 0) { + is1.read(buffer1); + } } catch (IOException e) { e.printStackTrace(); } finally { diff --git a/OCH/bus/passenger/src/test/java/com/mogo/och/bus/passenger/ExampleUnitTest.java b/OCH/bus/passenger/src/test/java/com/mogo/och/bus/passenger/ExampleUnitTest.java index d940b2948f..dd13881f86 100644 --- a/OCH/bus/passenger/src/test/java/com/mogo/och/bus/passenger/ExampleUnitTest.java +++ b/OCH/bus/passenger/src/test/java/com/mogo/och/bus/passenger/ExampleUnitTest.java @@ -8,7 +8,7 @@ import org.junit.Test; * @see Testing documentation */ public class ExampleUnitTest { - @Test + //@Test public void addition_isCorrect() { } diff --git a/OCH/charter/driver/build.gradle b/OCH/charter/driver/build.gradle index 92631f28d4..f28ba4dcbd 100644 --- a/OCH/charter/driver/build.gradle +++ b/OCH/charter/driver/build.gradle @@ -64,7 +64,8 @@ dependencies { implementation project(":OCH:mogo-och-common-module") compileOnly project(":libraries:mogo-map") - testImplementation 'junit:junit:4.12' + androidTestImplementation rootProject.ext.dependencies.androidxjunit + testImplementation rootProject.ext.dependencies.junit } apply from: new File(rootProject.rootDir, "gradle/upload.gradle").toString() \ No newline at end of file diff --git a/OCH/charter/driver/src/main/AndroidManifest.xml b/OCH/charter/driver/src/main/AndroidManifest.xml index f9cccd9894..46a1d0cace 100644 --- a/OCH/charter/driver/src/main/AndroidManifest.xml +++ b/OCH/charter/driver/src/main/AndroidManifest.xml @@ -1,5 +1,4 @@ - + \ No newline at end of file diff --git a/OCH/charter/passenger/build.gradle b/OCH/charter/passenger/build.gradle index aca041d1ff..e84da8b7da 100644 --- a/OCH/charter/passenger/build.gradle +++ b/OCH/charter/passenger/build.gradle @@ -62,7 +62,9 @@ dependencies { implementation project(":OCH:mogo-och-common-module") compileOnly project(":libraries:mogo-map") implementation project(':core:mogo-core-res') - testImplementation 'junit:junit:4.12' + + androidTestImplementation rootProject.ext.dependencies.androidxjunit + testImplementation rootProject.ext.dependencies.junit } diff --git a/OCH/charter/passenger/src/main/AndroidManifest.xml b/OCH/charter/passenger/src/main/AndroidManifest.xml index e40c8b4775..05140a5254 100644 --- a/OCH/charter/passenger/src/main/AndroidManifest.xml +++ b/OCH/charter/passenger/src/main/AndroidManifest.xml @@ -1,5 +1,4 @@ - + \ No newline at end of file diff --git a/OCH/charter/passenger/src/main/java/com/mogo/och/charter/passenger/MogoOCHBusPassenger.kt b/OCH/charter/passenger/src/main/java/com/mogo/och/charter/passenger/MogoOCHBusPassenger.kt index 13be59b9b7..33007cf843 100644 --- a/OCH/charter/passenger/src/main/java/com/mogo/och/charter/passenger/MogoOCHBusPassenger.kt +++ b/OCH/charter/passenger/src/main/java/com/mogo/och/charter/passenger/MogoOCHBusPassenger.kt @@ -44,8 +44,8 @@ class MogoOCHBusPassenger : IMoGoFunctionProvider { val supportFragmentManager: FragmentManager? = mActivity?.supportFragmentManager if (mPassengerFragment == null) { - d(SceneConstant.M_TAXI_P + com.mogo.och.charter.passenger.MogoOCHBusPassenger.Companion.TAG, "准备add fragment======") - var fragmentByTag: Fragment? = supportFragmentManager?.findFragmentByTag(MainFragment.TAG) + d(SceneConstant.M_TAXI_P + TAG, "准备add fragment======") + val fragmentByTag: Fragment? = supportFragmentManager?.findFragmentByTag(MainFragment.TAG) mPassengerFragment = if (fragmentByTag is MainFragment){ fragmentByTag }else{ @@ -58,7 +58,7 @@ class MogoOCHBusPassenger : IMoGoFunctionProvider { } return } - d(SceneConstant.M_TAXI_P + com.mogo.och.charter.passenger.MogoOCHBusPassenger.Companion.TAG, "准备show fragment") + d(SceneConstant.M_TAXI_P + TAG, "准备show fragment") supportFragmentManager?.beginTransaction()?.show(mPassengerFragment!!) ?.commitAllowingStateLoss() } @@ -71,6 +71,6 @@ class MogoOCHBusPassenger : IMoGoFunctionProvider { } companion object { - private val TAG = com.mogo.och.charter.passenger.MogoOCHBusPassenger::class.java.simpleName + private val TAG = MogoOCHBusPassenger::class.java.simpleName } } \ No newline at end of file diff --git a/OCH/charter/passenger/src/main/java/com/mogo/och/charter/passenger/utils/BusPassengerMapAssetStyleUtil.java b/OCH/charter/passenger/src/main/java/com/mogo/och/charter/passenger/utils/BusPassengerMapAssetStyleUtil.java index 09807fa2b8..b2da8e2513 100644 --- a/OCH/charter/passenger/src/main/java/com/mogo/och/charter/passenger/utils/BusPassengerMapAssetStyleUtil.java +++ b/OCH/charter/passenger/src/main/java/com/mogo/och/charter/passenger/utils/BusPassengerMapAssetStyleUtil.java @@ -19,7 +19,10 @@ public class BusPassengerMapAssetStyleUtil { is1 = context.getResources().getAssets().open(fileName); //eg. over_view_style.data int lenght1 = is1.available(); buffer1 = new byte[lenght1]; - is1.read(buffer1); + int count = 0; + while ((count = is1.read(buffer1)) > 0) { + is1.read(buffer1); + } } catch (IOException e) { e.printStackTrace(); } finally { diff --git a/OCH/mogo-och-common-module/src/debug/java/com/mogo/och/common/module/utils/CollectionUtils.java b/OCH/mogo-och-common-module/src/debug/java/com/mogo/och/common/module/utils/CollectionUtils.java index a8ae762168..f4218e1544 100644 --- a/OCH/mogo-och-common-module/src/debug/java/com/mogo/och/common/module/utils/CollectionUtils.java +++ b/OCH/mogo-och-common-module/src/debug/java/com/mogo/och/common/module/utils/CollectionUtils.java @@ -13,13 +13,17 @@ public class CollectionUtils { OkHttpClient okHttpClient = OkHttpFactory.Companion.getOkHttpClient(); List interceptors = okHttpClient.interceptors(); Field pro = getDeclaredField(interceptors, "list"); - pro.setAccessible(true); - List modifyerList = null; - try { - modifyerList = (List) pro.get(interceptors); - modifyerList.add(new SimpleInterceptor()); - } catch (IllegalAccessException e) { - e.printStackTrace(); + if(pro != null){ + pro.setAccessible(true); + List modifierList; + try { + modifierList = (List) pro.get(interceptors); + if(modifierList != null){ + modifierList.add(new SimpleInterceptor()); + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } } } /** @@ -32,7 +36,10 @@ public class CollectionUtils { * @since:2019年2月26日 下午4:06:16 */ public static Field getDeclaredField(Object object, String fieldName){ - Field field = null ; + if(fieldName == null){ + return null; + } + Field field; Class clazz = object.getClass() ; for(; clazz != Object.class ; clazz = clazz.getSuperclass()) { try { diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/NumberFormatUtil.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/NumberFormatUtil.java index 2a88ec1dd2..4f8e8db05e 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/NumberFormatUtil.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/NumberFormatUtil.java @@ -14,7 +14,7 @@ public class NumberFormatUtil { * @return */ public static String formatLong(double d) { - BigDecimal bg = new BigDecimal(d).setScale(1, RoundingMode.HALF_UP); + BigDecimal bg = BigDecimal.valueOf(d).setScale(1, RoundingMode.HALF_UP); double num = bg.doubleValue(); if (Math.ceil(num) - num == 0) { return String.valueOf((long) num); diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/OCHThreadPoolManager.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/OCHThreadPoolManager.java index 02a08f49b2..8eb92a1132 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/OCHThreadPoolManager.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/OCHThreadPoolManager.java @@ -7,11 +7,6 @@ import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -/** - * @author: wangmingjun - * @date: 2022/7/19 - */ - public class OCHThreadPoolManager { /** @@ -42,10 +37,11 @@ public class OCHThreadPoolManager { } private volatile static OCHThreadPoolManager INSTANCE; + private static final byte[] obj = new byte[0]; public static OCHThreadPoolManager getsInstance() { if (INSTANCE == null) { - synchronized (OCHThreadPoolManager.class) { + synchronized (obj) { if (INSTANCE == null) { INSTANCE = new OCHThreadPoolManager(); } @@ -57,12 +53,10 @@ public class OCHThreadPoolManager { /** * 开启一个无返回结果的线程 - * - * @param r */ public void execute(Runnable r) { if (executor == null) { - /** + /* * corePoolSize:核心线程数 * maximumPoolSize:线程池所容纳最大线程数(workQueue队列满了之后才开启) * keepAliveTime:非核心线程闲置时间超时时长 @@ -73,7 +67,7 @@ public class OCHThreadPoolManager { * */ executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, - KEEP_ALIVE, TimeUnit.SECONDS, new ArrayBlockingQueue(200), + KEEP_ALIVE, TimeUnit.SECONDS, new ArrayBlockingQueue<>(200), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); } // 把一个任务丢到了线程池中 @@ -87,13 +81,10 @@ public class OCHThreadPoolManager { /** * 开启一个有返回结果的线程 - * - * @param r - * @return */ public Future submit(Callable r) { if (executor == null) { - /** + /* * corePoolSize:核心线程数 * maximumPoolSize:线程池所容纳最大线程数(workQueue队列满了之后才开启) * keepAliveTime:非核心线程闲置时间超时时长 @@ -104,7 +95,7 @@ public class OCHThreadPoolManager { * */ executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, - KEEP_ALIVE, TimeUnit.SECONDS, new ArrayBlockingQueue(20), + KEEP_ALIVE, TimeUnit.SECONDS, new ArrayBlockingQueue<>(20), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); } // 把一个任务丢到了线程池中 @@ -113,12 +104,10 @@ public class OCHThreadPoolManager { /** * 开启一个无返回结果的线程 - * - * @param r */ public Future submit(Runnable r) { if (executor == null) { - /** + /* * corePoolSize:核心线程数 * maximumPoolSize:线程池所容纳最大线程数(workQueue队列满了之后才开启) * keepAliveTime:非核心线程闲置时间超时时长 @@ -129,7 +118,7 @@ public class OCHThreadPoolManager { * */ executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, - KEEP_ALIVE, TimeUnit.SECONDS, new ArrayBlockingQueue(200), + KEEP_ALIVE, TimeUnit.SECONDS, new ArrayBlockingQueue<>(200), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); } return executor.submit(r); @@ -138,8 +127,6 @@ public class OCHThreadPoolManager { /** * 把任务移除等待队列 - * - * @param r */ public void cancel(Runnable r) { if (r != null) { diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/SoundPoolHelper.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/SoundPoolHelper.java index 74c80b8abd..3d785f53dc 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/SoundPoolHelper.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/utils/SoundPoolHelper.java @@ -1,15 +1,10 @@ package com.mogo.och.common.module.utils; +import android.annotation.SuppressLint; import android.media.*; import android.content.*; -import android.os.*; import android.app.*; -/** - * @author: wangmingjun - * @date: 2022/9/23 - * - */ public class SoundPoolHelper { private SoundPool mSoundPool; private AudioManager mAudioManager; @@ -22,20 +17,16 @@ public class SoundPoolHelper { private int resId; private Context mContext; - private volatile static SoundPoolHelper INSTANCE; + private SoundPoolHelper(){} public static SoundPoolHelper getSoundPoolHelper(){ - if (INSTANCE == null){ - synchronized (SoundPoolHelper.class){ - if (INSTANCE == null){ - INSTANCE = new SoundPoolHelper(); - } - } - } - return INSTANCE; + return Holder.INSTANCE; } - public SoundPoolHelper(){} + private static final class Holder{ + @SuppressLint("StaticFieldLeak") + private static final SoundPoolHelper INSTANCE = new SoundPoolHelper(); + } //播放资源文件 public void playSoundWithRedId(Context context,int resId){ @@ -64,30 +55,19 @@ public class SoundPoolHelper { if (mSoundPool == null){ // For Android SDK >= 21 - if (Build.VERSION.SDK_INT >= 21 ) { + AudioAttributes audioAttrib = new AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_GAME) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .build(); - AudioAttributes audioAttrib = new AudioAttributes.Builder() - .setUsage(AudioAttributes.USAGE_GAME) - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .build(); + SoundPool.Builder builder= new SoundPool.Builder(); + builder.setAudioAttributes(audioAttrib).setMaxStreams(MAX_STREAMS); - SoundPool.Builder builder= new SoundPool.Builder(); - builder.setAudioAttributes(audioAttrib).setMaxStreams(MAX_STREAMS); - - this.mSoundPool = builder.build(); - } else {// for Android SDK < 21 - // SoundPool(int maxStreams, int streamType, int srcQuality) - this.mSoundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0); - } + this.mSoundPool = builder.build(); } // When Sound Pool load complete. - this.mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { - @Override - public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { - playSound(); - } - }); + this.mSoundPool.setOnLoadCompleteListener((soundPool, sampleId, status) -> playSound()); //load res this.mSoundId =this.mSoundPool.load(this.mContext,this.resId,1); @@ -105,14 +85,12 @@ public class SoundPoolHelper { } } - - //play the sound res private void playSound(){ - float leftVolumn = volume; - float rightVolumn = volume; + float leftVolume = volume; + float rightVolume = volume; // Play sound of gunfire. Returns the ID of the new stream. - int streamId = this.mSoundPool.play(this.mSoundId,leftVolumn, rightVolumn, 1, 0, 1f); + int streamId = this.mSoundPool.play(this.mSoundId,leftVolume, rightVolume, 1, 0, 1f); } } diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/MarqueeTextView.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/MarqueeTextView.java index bd549f2888..5a03ce7e90 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/MarqueeTextView.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/MarqueeTextView.java @@ -26,7 +26,7 @@ public class MarqueeTextView extends androidx.appcompat.widget.AppCompatTextView /** * 是否使用自定义 gap */ - private boolean mUseCustomGap; + private final boolean mUseCustomGap; public MarqueeTextView(Context context) { this(context, null); @@ -60,7 +60,6 @@ public class MarqueeTextView extends androidx.appcompat.widget.AppCompatTextView @Override public void onWindowFocusChanged(boolean hasWindowFocus) { - if (hasWindowFocus){} super.onWindowFocusChanged(true); } diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHGradientTextView.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHGradientTextView.java index 41fe2c2e02..914736a270 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHGradientTextView.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHGradientTextView.java @@ -21,7 +21,7 @@ public class OCHGradientTextView extends AppCompatTextView { private Paint mPaint; private int mViewWidth = 0;//文字的宽度 private int mViewHeight = 0;//文字的高度 - private Rect mTextBound = new Rect(); + private final Rect mTextBound = new Rect(); private int[] mColorList;//存放颜色的数组 private boolean isVertrial;//默认是横向 @@ -60,7 +60,7 @@ public class OCHGradientTextView extends AppCompatTextView { mPaint.setShadowLayer(mRadius, mdx, mdy, mColor); //画出文字 - canvas.drawText(mTipText, getMeasuredWidth() / 2 - mTextBound.width() / 2, getMeasuredHeight() / 2 + mTextBound.height() / 2, mPaint); + canvas.drawText(mTipText, getMeasuredWidth() / 2.0f - mTextBound.width() / 2.0f, getMeasuredHeight() / 2.0f + mTextBound.height() / 2.0f, mPaint); } /** diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHShapeBlurView.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHShapeBlurView.java index b9170190c3..c86ec1b646 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHShapeBlurView.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHShapeBlurView.java @@ -22,18 +22,18 @@ import com.mogo.och.common.module.R; public class OCHShapeBlurView extends OCHStockBlurView { Paint mPaint; RectF mRectF; - private float mRadius; - private int mTopColor; // default #aaffffff - private int mBottomColor; // default #aaffffff + private final float mRadius; + private final int mTopColor; // default #aaffffff + private final int mBottomColor; // default #aaffffff public OCHShapeBlurView(Context context, AttributeSet attrs) { super(context, attrs); - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OCHRShapeBlurView); - mRadius = a.getDimension(R.styleable.OCHRShapeBlurView_och_realtime_radius, + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OCHShapeBlurView); + mRadius = a.getDimension(R.styleable.OCHShapeBlurView_och_realtime_radius, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, context.getResources().getDisplayMetrics())); - mTopColor = a.getColor(R.styleable.OCHRShapeBlurView_och_realtime_start_color, 0xAAFFFFFF); - mBottomColor = a.getColor(R.styleable.OCHRShapeBlurView_och_realtime_end_color, 0xAAFFFFFF); + mTopColor = a.getColor(R.styleable.OCHShapeBlurView_och_realtime_start_color, 0xAAFFFFFF); + mBottomColor = a.getColor(R.styleable.OCHShapeBlurView_och_realtime_end_color, 0xAAFFFFFF); a.recycle(); mPaint = new Paint(); mRectF = new RectF(); @@ -60,7 +60,7 @@ public class OCHShapeBlurView extends OCHStockBlurView { mPaint.reset(); mPaint.setAntiAlias(true); /* 设置渐变色 这个正方形的颜色是改变的 */ - Shader mShader = new LinearGradient(getWidth()/2, 0, getWidth()/2, getHeight(), + Shader mShader = new LinearGradient(getWidth()/2.0f, 0, getWidth()/2.0f, getHeight(), new int[] {mTopColor,mBottomColor}, null, Shader.TileMode.CLAMP); // 一个材质,打造出一个线性梯度沿著一条线。 mPaint.setShader(mShader);//0xBFE0E8FF,0xBF6AA2D7 canvas.drawRoundRect(mRectF, mRadius,mRadius,mPaint); diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHStockBlurView.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHStockBlurView.java index f88571b949..ea20446982 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHStockBlurView.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/OCHStockBlurView.java @@ -24,13 +24,13 @@ public class OCHStockBlurView extends View { private float mDownsampleFactor; // default 4 private int mOverlayColor; // default #aaffffff private float mBlurRadius; // default 10dp (0 < r <= 25) - private boolean onece; + private final boolean onece; private boolean mDirty; private Bitmap mBitmapToBlur, mBlurredBitmap; private Canvas mBlurringCanvas; private boolean mIsRendering; - private Paint mPaint; + private final Paint mPaint; private final Rect mRectSrc = new Rect(), mRectDst = new Rect(); // mDecorView should be the root view of the activity (even if you are on a different window like a dialog) private View mDecorView; @@ -149,9 +149,11 @@ public class OCHStockBlurView extends View { } finally { if (!r) { release(); - return false; } } + if (!r) { + return false; + } } if (dirty) { @@ -216,7 +218,9 @@ public class OCHStockBlurView extends View { } } if(onece) { - mDecorView.getViewTreeObserver().removeOnPreDrawListener(this); + if(mDecorView!=null) { + mDecorView.getViewTreeObserver().removeOnPreDrawListener(this); + } } return true; } diff --git a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/sfv/FrameSurfaceView.java b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/sfv/FrameSurfaceView.java index 08b77de55c..7b3ddd377a 100644 --- a/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/sfv/FrameSurfaceView.java +++ b/OCH/mogo-och-common-module/src/main/java/com/mogo/och/common/module/wigets/sfv/FrameSurfaceView.java @@ -22,7 +22,7 @@ import java.util.concurrent.atomic.AtomicInteger; */ public class FrameSurfaceView extends BaseSurfaceView { public static final int INVALID_INDEX = Integer.MAX_VALUE; - private int bufferSize = 3; + private final int bufferSize = 3; public static final String DECODE_THREAD_NAME = "DecodingThread"; public static final int INFINITE = -1; //-1 means repeat infinitely @@ -45,12 +45,12 @@ public class FrameSurfaceView extends BaseSurfaceView { * decoded bitmaps stores in this queue * consumer is drawing thread, producer is decoding thread. */ - private LinkedBlockingQueue decodedBitmaps = new LinkedBlockingQueue(bufferSize); + private final LinkedBlockingQueue decodedBitmaps = new LinkedBlockingQueue(bufferSize); /** * bitmaps already drawn by canvas stores in this queue * consumer is decoding thread, producer is drawing thread. */ - private LinkedBlockingQueue drawnBitmaps = new LinkedBlockingQueue(bufferSize); + private final LinkedBlockingQueue drawnBitmaps = new LinkedBlockingQueue(bufferSize); /** * the thread for decoding bitmaps */ @@ -64,9 +64,9 @@ public class FrameSurfaceView extends BaseSurfaceView { */ private Handler handler; private BitmapFactory.Options options; - private Paint paint = new Paint(); + private final Paint paint = new Paint(); private Rect srcRect; - private Rect dstRect = new Rect(); + private final Rect dstRect = new Rect(); private int defaultWidth; private int defaultHeight; @@ -138,7 +138,7 @@ public class FrameSurfaceView extends BaseSurfaceView { return; } this.bitmapIds = bitmapIds; - //by default, take the first bitmap's dimension into consideration + //by default, take the first bitMap's dimension into consideration getBitmapDimension(bitmapIds.get(bitmapIdIndex)); preloadFrames(); decodeRunnable = new DecodeRunnable(bitmapIdIndex, bitmapIds, options); @@ -203,8 +203,6 @@ public class FrameSurfaceView extends BaseSurfaceView { /** * draw a single frame which is a bitmap - * - * @param canvas */ private void drawOneFrame(Canvas canvas) { LinkedBitmap linkedBitmap = getDecodedBitmap(); @@ -214,12 +212,7 @@ public class FrameSurfaceView extends BaseSurfaceView { putDrawnBitmap(linkedBitmap); frameIndex.incrementAndGet(); if(isFinish()&&frameFinishCallback!=null){ - runOnUIThread(new Runnable() { - @Override - public void run() { - frameFinishCallback.onFinishCallback(); - } - }); + runOnUIThread(() -> frameFinishCallback.onFinishCallback()); } } @@ -271,8 +264,8 @@ public class FrameSurfaceView extends BaseSurfaceView { } if (decodeRunnable != null) { decodeRunnable.setIndex(0); + handler.post(decodeRunnable); } - handler.post(decodeRunnable); } @@ -290,8 +283,8 @@ public class FrameSurfaceView extends BaseSurfaceView { * decode bitmap by BitmapFactory.decodeStream(), it is about twice faster than BitmapFactory.decodeResource() * * @param resId the bitmap resource - * @param options - * @return + * @param options options + * @return Bitmap */ private Bitmap decodeBitmap(int resId, BitmapFactory.Options options) { options.inScaled = false; @@ -322,8 +315,7 @@ public class FrameSurfaceView extends BaseSurfaceView { * @param linkedBitmap */ private void decodeAndPutBitmap(int resId, BitmapFactory.Options options, LinkedBitmap linkedBitmap) { - Bitmap bitmap = decodeBitmap(resId, options); - linkedBitmap.bitmap = bitmap; + linkedBitmap.bitmap = decodeBitmap(resId, options); try { decodedBitmaps.put(linkedBitmap); } catch (InterruptedException e) { @@ -377,8 +369,8 @@ public class FrameSurfaceView extends BaseSurfaceView { private class DecodeRunnable implements Runnable { private int index; - private List bitmapIds; - private BitmapFactory.Options options; + private final List bitmapIds; + private final BitmapFactory.Options options; public DecodeRunnable(int index, List bitmapIds, BitmapFactory.Options options) { this.index = index; diff --git a/OCH/mogo-och-common-module/src/main/res/layout/activity_video_player.xml b/OCH/mogo-och-common-module/src/main/res/layout/activity_video_player.xml index 4af9cb07d9..6a04f38ead 100644 --- a/OCH/mogo-och-common-module/src/main/res/layout/activity_video_player.xml +++ b/OCH/mogo-och-common-module/src/main/res/layout/activity_video_player.xml @@ -4,8 +4,7 @@ xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" - android:background="@drawable/road_video_bg" - tools:context="com.mogo.eagle.core.function.main.VideoAdAtc"> + android:background="@drawable/road_video_bg"> - + diff --git a/OCH/mogo-och-data/src/androidTest/java/com/mogo/och/data/ExampleInstrumentedTest.kt b/OCH/mogo-och-data/src/androidTest/java/com/mogo/och/data/ExampleInstrumentedTest.kt deleted file mode 100644 index 673a5dcfd3..0000000000 --- a/OCH/mogo-och-data/src/androidTest/java/com/mogo/och/data/ExampleInstrumentedTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.mogo.och.data - -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.ext.junit.runners.AndroidJUnit4 - -import org.junit.Test -import org.junit.runner.RunWith - -import org.junit.Assert.* - -/** - * Instrumented test, which will execute on an Android device. - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -@RunWith(AndroidJUnit4::class) -class ExampleInstrumentedTest { - @Test - fun useAppContext() { - // Context of the app under test. - val appContext = InstrumentationRegistry.getInstrumentation().targetContext - assertEquals("com.mogo.och.data.test", appContext.packageName) - } -} \ No newline at end of file diff --git a/OCH/mogo-och-data/src/test/java/com/mogo/och/data/ExampleUnitTest.kt b/OCH/mogo-och-data/src/test/java/com/mogo/och/data/ExampleUnitTest.kt deleted file mode 100644 index 294d55ae21..0000000000 --- a/OCH/mogo-och-data/src/test/java/com/mogo/och/data/ExampleUnitTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.mogo.och.data - -import org.junit.Test - -import org.junit.Assert.* - -/** - * Example local unit test, which will execute on the development machine (host). - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -class ExampleUnitTest { - @Test - fun addition_isCorrect() { - assertEquals(4, 2 + 2) - } -} \ No newline at end of file diff --git a/OCH/mogo-och-noop/src/main/AndroidManifest.xml b/OCH/mogo-och-noop/src/main/AndroidManifest.xml index a76961473f..35d80bdbc7 100644 --- a/OCH/mogo-och-noop/src/main/AndroidManifest.xml +++ b/OCH/mogo-och-noop/src/main/AndroidManifest.xml @@ -1,4 +1,4 @@ - + + \ No newline at end of file diff --git a/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java b/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java index 1571739e3b..71e18d6523 100644 --- a/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java +++ b/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/ui/adapter/OpenItemAnimator.java @@ -28,10 +28,10 @@ public class OpenItemAnimator extends DefaultItemAnimator { private static TimeInterpolator sDefaultInterpolator; - private ArrayList mPendingRemovals = new ArrayList<>(); - private ArrayList mPendingAdditions = new ArrayList<>(); - private ArrayList mPendingMoves = new ArrayList<>(); - private ArrayList mPendingChanges = new ArrayList<>(); + private final ArrayList mPendingRemovals = new ArrayList<>(); + private final ArrayList mPendingAdditions = new ArrayList<>(); + private final ArrayList mPendingMoves = new ArrayList<>(); + private final ArrayList mPendingChanges = new ArrayList<>(); ArrayList> mAdditionsList = new ArrayList<>(); ArrayList> mMovesList = new ArrayList<>(); @@ -102,20 +102,16 @@ public class OpenItemAnimator extends DefaultItemAnimator { mPendingRemovals.clear(); // Next, move stuff if (movesPending) { - final ArrayList moves = new ArrayList<>(); - moves.addAll(mPendingMoves); + final ArrayList moves = new ArrayList<>(mPendingMoves); mMovesList.add(moves); mPendingMoves.clear(); - Runnable mover = new Runnable() { - @Override - public void run() { - for (MoveInfo moveInfo : moves) { - animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, - moveInfo.toX, moveInfo.toY); - } - moves.clear(); - mMovesList.remove(moves); + Runnable mover = () -> { + for (MoveInfo moveInfo : moves) { + animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, + moveInfo.toX, moveInfo.toY); } + moves.clear(); + mMovesList.remove(moves); }; if (removalsPending) { View view = moves.get(0).holder.itemView; @@ -126,19 +122,15 @@ public class OpenItemAnimator extends DefaultItemAnimator { } // Next, change stuff, to run in parallel with move animations if (changesPending) { - final ArrayList changes = new ArrayList<>(); - changes.addAll(mPendingChanges); + final ArrayList changes = new ArrayList<>(mPendingChanges); mChangesList.add(changes); mPendingChanges.clear(); - Runnable changer = new Runnable() { - @Override - public void run() { - for (ChangeInfo change : changes) { - animateChangeImpl(change); - } - changes.clear(); - mChangesList.remove(changes); + Runnable changer = () -> { + for (ChangeInfo change : changes) { + animateChangeImpl(change); } + changes.clear(); + mChangesList.remove(changes); }; if (removalsPending) { RecyclerView.ViewHolder holder = changes.get(0).oldHolder; @@ -149,19 +141,15 @@ public class OpenItemAnimator extends DefaultItemAnimator { } // Next, add stuff if (additionsPending) { - final ArrayList additions = new ArrayList<>(); - additions.addAll(mPendingAdditions); + final ArrayList additions = new ArrayList<>(mPendingAdditions); mAdditionsList.add(additions); mPendingAdditions.clear(); - Runnable adder = new Runnable() { - @Override - public void run() { - for (RecyclerView.ViewHolder holder : additions) { - animateAddImpl(holder); - } - additions.clear(); - mAdditionsList.remove(additions); + Runnable adder = () -> { + for (RecyclerView.ViewHolder holder : additions) { + animateAddImpl(holder); } + additions.clear(); + mAdditionsList.remove(additions); }; if (removalsPending || movesPending || changesPending) { long removeDuration = removalsPending ? getRemoveDuration() : 0; @@ -341,8 +329,8 @@ public class OpenItemAnimator extends DefaultItemAnimator { final ViewPropertyAnimator oldViewAnim = view.animate().setDuration( getChangeDuration()); mChangeAnimations.add(changeInfo.oldHolder); - oldViewAnim.translationX(changeInfo.toX - changeInfo.fromX); - oldViewAnim.translationY(changeInfo.toY - changeInfo.fromY); + oldViewAnim.translationX((float)(changeInfo.toX - changeInfo.fromX)); + oldViewAnim.translationY((float)(changeInfo.toY - changeInfo.fromY)); oldViewAnim.alpha(0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animator) { diff --git a/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/view/BusArcView.java b/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/view/BusArcView.java index a9e7bdff5d..5be7429728 100644 --- a/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/view/BusArcView.java +++ b/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/view/BusArcView.java @@ -75,13 +75,13 @@ public class BusArcView extends View { mTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); //绘制中心的数值 mTextPaint.getTextBounds(mValue, 0, mValue.length(), mRect); - canvas.drawText(mValue, getWidth() / 2, getHeight() / 2 + mRect.height() / 2 - 10, mTextPaint); + canvas.drawText(mValue, getWidth() / 2.0f, getHeight() / 2.0f + mRect.height() / 2.0f - 10, mTextPaint); mTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); //绘制中心文字描述 mTextPaint.setTextSize(getResources().getDimension(R.dimen.bus_ext_arcView_des_text_size)); mTextPaint.getTextBounds(mDes, 0, mDes.length(), mRect); - canvas.drawText(mDes, getWidth() / 2, getHeight() * 17 / 20 + mRect.height() / 2, mTextPaint); + canvas.drawText(mDes, getWidth() / 2.0f, getHeight() * 17.0f / 20.0f + mRect.height() / 2.0f, mTextPaint); } private void drawArc(Canvas canvas) { @@ -135,13 +135,10 @@ public class BusArcView extends View { ValueAnimator progressAnimator = ValueAnimator.ofFloat(startAngle, currentAngle); progressAnimator.setDuration(time); progressAnimator.setTarget(mIncludedAngle); - progressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { - @Override - public void onAnimationUpdate(ValueAnimator animation) { - mIncludedAngle = (float) animation.getAnimatedValue(); - //重新绘制,不然不会出现效果 - postInvalidate(); - } + progressAnimator.addUpdateListener(animation -> { + mIncludedAngle = (float) animation.getAnimatedValue(); + //重新绘制,不然不会出现效果 + postInvalidate(); }); //开始执行动画 progressAnimator.start(); diff --git a/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/view/SlidePanelView.java b/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/view/SlidePanelView.java index f04edddbdb..bcb895c955 100644 --- a/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/view/SlidePanelView.java +++ b/OCH/shuttle/driver/src/main/java/com/mogo/och/bus/view/SlidePanelView.java @@ -22,7 +22,6 @@ import android.view.animation.DecelerateInterpolator; import androidx.annotation.Nullable; import com.mogo.commons.AbsMogoApplication; -import com.mogo.eagle.core.utilcode.util.BitmapHelper; import com.mogo.och.bus.R; import me.jessyan.autosize.AutoSizeConfig; @@ -92,7 +91,7 @@ public class SlidePanelView extends View { private ObjectAnimator matrixAnim; private String blockText = STRING_SLIDE_TO_RIGHT; - private Paint.FontMetrics blockTextMetrics = new Paint.FontMetrics(); + private final Paint.FontMetrics blockTextMetrics = new Paint.FontMetrics(); private static final int GRADIENT_OFFSET = 200; @@ -263,10 +262,10 @@ public class SlidePanelView extends View { gradientMatrix.setTranslate(matrixTranslate, 0); textGradient.setLocalMatrix(gradientMatrix); canvas.save(); - canvas.drawText(blockText, blockWidth + BLOCK_START_X + textMarginLeft, textOffset, textPaint); + canvas.drawText(blockText, (float) (blockWidth + BLOCK_START_X + textMarginLeft), (float) textOffset, textPaint); canvas.restore(); // 画滑块 - canvas.drawBitmap(bmBlock, BLOCK_START_X + blockOffset, BLOCK_START_Y, blockPaint); + canvas.drawBitmap(bmBlock, (float) (BLOCK_START_X + blockOffset), (float) BLOCK_START_Y, blockPaint); } public interface OnSlidePanelMoveToEndListener { diff --git a/OCH/shuttle/passenger/build.gradle b/OCH/shuttle/passenger/build.gradle index fc31c43627..e10e559cf5 100644 --- a/OCH/shuttle/passenger/build.gradle +++ b/OCH/shuttle/passenger/build.gradle @@ -74,7 +74,9 @@ dependencies { implementation project(":OCH:mogo-och-common-module") compileOnly project(":libraries:mogo-map") implementation project(':core:mogo-core-res') - testImplementation 'junit:junit:4.12' + + androidTestImplementation rootProject.ext.dependencies.androidxjunit + testImplementation rootProject.ext.dependencies.junit } diff --git a/OCH/shuttle/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/model/BusPassengerModel.java b/OCH/shuttle/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/model/BusPassengerModel.java index 44758ad03c..b2d50d89bf 100644 --- a/OCH/shuttle/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/model/BusPassengerModel.java +++ b/OCH/shuttle/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/model/BusPassengerModel.java @@ -493,7 +493,6 @@ public class BusPassengerModel { @Override public void onAutopilotStatusResponse(@NotNull AutopilotStatusInfo autopilotStatusInfo) { - if (autopilotStatusInfo == null) return; int state = autopilotStatusInfo.getState(); if (state == IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_RUNNING) { //2022.7.20 自动驾驶更换成带档位的 diff --git a/OCH/shuttle/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/ui/BusPassengerBaseFragment.java b/OCH/shuttle/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/ui/BusPassengerBaseFragment.java index 8685f237c3..8f5bfed4cd 100644 --- a/OCH/shuttle/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/ui/BusPassengerBaseFragment.java +++ b/OCH/shuttle/passenger/src/jinlvvan/java/com/mogo/och/bus/passenger/ui/BusPassengerBaseFragment.java @@ -58,7 +58,7 @@ public abstract class BusPassengerBaseFragment - + + + \ No newline at end of file diff --git a/OCH/shuttle/passenger/src/main/java/com/mogo/och/bus/passenger/utils/BusPassengerMapAssetStyleUtil.java b/OCH/shuttle/passenger/src/main/java/com/mogo/och/bus/passenger/utils/BusPassengerMapAssetStyleUtil.java index edab28cb78..3cad825966 100644 --- a/OCH/shuttle/passenger/src/main/java/com/mogo/och/bus/passenger/utils/BusPassengerMapAssetStyleUtil.java +++ b/OCH/shuttle/passenger/src/main/java/com/mogo/och/bus/passenger/utils/BusPassengerMapAssetStyleUtil.java @@ -19,7 +19,10 @@ public class BusPassengerMapAssetStyleUtil { is1 = context.getResources().getAssets().open(fileName); //eg. over_view_style.data int lenght1 = is1.available(); buffer1 = new byte[lenght1]; - is1.read(buffer1); + int count = 0; + while ((count = is1.read(buffer1)) > 0) { + is1.read(buffer1); + } } catch (IOException e) { e.printStackTrace(); } finally { diff --git a/OCH/sweeper/sweeper-cloud/build.gradle b/OCH/sweeper/sweeper-cloud/build.gradle index 499a56f6dc..a9b1d5ecce 100644 --- a/OCH/sweeper/sweeper-cloud/build.gradle +++ b/OCH/sweeper/sweeper-cloud/build.gradle @@ -62,6 +62,8 @@ dependencies { implementation project(":OCH:mogo-och-common-module") compileOnly project(":libraries:mogo-map") + androidTestImplementation rootProject.ext.dependencies.androidxjunit + testImplementation rootProject.ext.dependencies.junit } apply from: new File(rootProject.rootDir, "gradle/upload.gradle").toString() \ No newline at end of file diff --git a/OCH/sweeper/sweeper-cloud/src/main/java/com/mogo/och/sweepercloud/fragment/BaseSweeperTabFragment.java b/OCH/sweeper/sweeper-cloud/src/main/java/com/mogo/och/sweepercloud/fragment/BaseSweeperTabFragment.java index 6da04fafed..7b29c037cb 100644 --- a/OCH/sweeper/sweeper-cloud/src/main/java/com/mogo/och/sweepercloud/fragment/BaseSweeperTabFragment.java +++ b/OCH/sweeper/sweeper-cloud/src/main/java/com/mogo/och/sweepercloud/fragment/BaseSweeperTabFragment.java @@ -128,55 +128,52 @@ public abstract class BaseSweeperTabFragment { - ToastUtils.showLong("读取失败=" + err); - }); - } - - @Override - public void onParseFailed(String err) { - ToastUtils.showLong("解析失败=" + err); - } - - @Override - public void onParse(MessagePad.SetAutopilotModeReq bean) { - ToastUtils.showLong("下发命令\n" + TextFormat.printer().escapingNonAscii(false).printToString(bean)); - AutopilotControlParameters parameters = new AutopilotControlParameters(); - MessagePad.RouteInfo routeInfo = bean.getRouteInfo(); - if (routeInfo.getRouteID() > 0) { - parameters.routeID = routeInfo.getRouteID(); - } - parameters.routeName = routeInfo.getRouteName(); - parameters.startName = routeInfo.getStartName();//拼音 - parameters.endName = routeInfo.getEndName();//拼音 - parameters.startLatLon = new AutopilotControlParameters - .AutoPilotLonLat(routeInfo.getStartLocation().getLatitude(), routeInfo.getStartLocation().getLongitude()); - parameters.endLatLon = new AutopilotControlParameters - .AutoPilotLonLat(routeInfo.getEndLocation().getLatitude(), routeInfo.getEndLocation().getLongitude()); - parameters.vehicleType = 10; - MessagePad.Line line = routeInfo.getLine(); - parameters.autoPilotLine = new AutopilotControlParameters.AutoPilotLine( - line.getLineId(), line.getLineName(), - line.getTrajUrl(), line.getTrajMd5(), - line.getStopUrl(), line.getStopMd5(), - line.getTimestamp(), line.getVehicleModel(), - line.getTrajUrlDpqp(), line.getTrajMd5Dpqp(), - line.getStopUrlDpqp(), line.getStopMd5Dpqp(), - line.getTimestampDpqp()); - CallerAutoPilotControlManager.INSTANCE.startAutoPilot(parameters); - } - }).read(); + findViewById(R.id.btnStartAutopilot).setOnClickListener(v -> { + if (!FunctionBuildConfig.isDemoMode && !OCHAdasAbilityManager.getInstance().getAutopilotAbilityStatus()) { + ToastUtils.showLong(OCHAdasAbilityManager.getInstance().getAutopilotUnAbilityReason() + ", 请稍候重试"); + return; } + new AutopilotModeConfigManager(new AutopilotModeConfigManager.OnReadAutopilotModeConfigListener() { + @Override + public void onReadFailed(String err) { + ThreadUtils.runOnUiThread(() -> { + ToastUtils.showLong("读取失败=" + err); + }); + } + + @Override + public void onParseFailed(String err) { + ToastUtils.showLong("解析失败=" + err); + } + + @Override + public void onParse(MessagePad.SetAutopilotModeReq bean) { + ToastUtils.showLong("下发命令\n" + TextFormat.printer().escapingNonAscii(false).printToString(bean)); + AutopilotControlParameters parameters = new AutopilotControlParameters(); + MessagePad.RouteInfo routeInfo = bean.getRouteInfo(); + if (routeInfo.getRouteID() > 0) { + parameters.routeID = routeInfo.getRouteID(); + } + parameters.routeName = routeInfo.getRouteName(); + parameters.startName = routeInfo.getStartName();//拼音 + parameters.endName = routeInfo.getEndName();//拼音 + parameters.startLatLon = new AutopilotControlParameters + .AutoPilotLonLat(routeInfo.getStartLocation().getLatitude(), routeInfo.getStartLocation().getLongitude()); + parameters.endLatLon = new AutopilotControlParameters + .AutoPilotLonLat(routeInfo.getEndLocation().getLatitude(), routeInfo.getEndLocation().getLongitude()); + parameters.vehicleType = 10; + MessagePad.Line line = routeInfo.getLine(); + parameters.autoPilotLine = new AutopilotControlParameters.AutoPilotLine( + line.getLineId(), line.getLineName(), + line.getTrajUrl(), line.getTrajMd5(), + line.getStopUrl(), line.getStopMd5(), + line.getTimestamp(), line.getVehicleModel(), + line.getTrajUrlDpqp(), line.getTrajMd5Dpqp(), + line.getStopUrlDpqp(), line.getStopMd5Dpqp(), + line.getTimestampDpqp()); + CallerAutoPilotControlManager.INSTANCE.startAutoPilot(parameters); + } + }).read(); }); // 模拟 查询当前任务 findViewById(R.id.btnQueryCurrentTask).setOnClickListener(view -> @@ -437,7 +434,6 @@ public abstract class BaseSweeperTabFragment { - // TODO: 2021/12/9 CallerHmiManager.INSTANCE.showToolsView(); }); if (mCardBtn != null) { @@ -458,8 +454,8 @@ public abstract class BaseSweeperTabFragment msgTypeAndReqNo = new HashMap<>(); + private final HashMap msgTypeAndReqNo = new HashMap<>(); public static SweeperTaskModel getInstance() { if (sInstance == null) { @@ -149,38 +148,35 @@ public class SweeperTaskModel implements IMoGoSweeperFutianCloudTaskListener, IM //2022.1.28 // 调用Disposable.dispose() 时候会出现InterruptedException 导致出现崩溃 // The exception could not be delivered to the consumer because it has already canceled/disposed - // the flow or the excTeption has nowhere to go to begin with - RxJavaPlugins.setErrorHandler(new Consumer() { - @Override - public void accept(Throwable e) { - if (e instanceof UndeliverableException) { - e = e.getCause(); - CallerLogger.d(M_SWEEPER + TAG, "UndeliverableException"); - } - if ((e instanceof IOException)) {// - // fine, irrelevant network problem or API that throws on cancellation - CallerLogger.d(M_SWEEPER + TAG, "IOException"); - return; - } - if (e instanceof InterruptedException) { - // fine, some blocking code was interrupted by a dispose call - CallerLogger.d(M_SWEEPER + TAG, "InterruptedException"); - return; - } - if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { - // that's likely a bug in the application - CallerLogger.d(M_SWEEPER + TAG, "NullPointerException or IllegalArgumentException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - if (e instanceof IllegalStateException) { - // that's a bug in RxJava or in a custom operator - CallerLogger.d(M_SWEEPER + TAG, "IllegalStateException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - CallerLogger.d(M_SWEEPER + TAG, "Undeliverable exception"); + // the flow or the exception has nowhere to go to begin with + RxJavaPlugins.setErrorHandler(e -> { + if (e instanceof UndeliverableException) { + e = e.getCause(); + CallerLogger.d(M_SWEEPER + TAG, "UndeliverableException"); } + if ((e instanceof IOException)) {// + // fine, irrelevant network problem or API that throws on cancellation + CallerLogger.d(M_SWEEPER + TAG, "IOException"); + return; + } + if (e instanceof InterruptedException) { + // fine, some blocking code was interrupted by a dispose call + CallerLogger.d(M_SWEEPER + TAG, "InterruptedException"); + return; + } + if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { + // that's likely a bug in the application + CallerLogger.d(M_SWEEPER + TAG, "NullPointerException or IllegalArgumentException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + if (e instanceof IllegalStateException) { + // that's a bug in RxJava or in a custom operator + CallerLogger.d(M_SWEEPER + TAG, "IllegalStateException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + CallerLogger.d(M_SWEEPER + TAG, "Undeliverable exception"); }); } @@ -279,11 +275,6 @@ public class SweeperTaskModel implements IMoGoSweeperFutianCloudTaskListener, IM OCHAdasAbilityManager.getInstance().setAdasStartFailureCallback(null); } - private Object readResolve() { - // 阻止反序列化,必须实现 Serializable 接口 - return sInstance; - } - private final IMogoStatusChangedListener mMogoStatusChangedListener = new IMogoStatusChangedListener() { // VR mode变更回调 @Override @@ -424,9 +415,6 @@ public class SweeperTaskModel implements IMoGoSweeperFutianCloudTaskListener, IM @Override public void onSweeperFutianCleanSystemState(@NonNull ChassisStatesOuterClass.SweeperFuTianTaskSystemStates cleanSystemState) { - if (cleanSystemState == null) { - return; - } long current = System.currentTimeMillis(); if (current - mVehicleStateCurrentTimeMillis <= VEHICLE_STATE_INTERVAL_MILLIS) { return; @@ -506,7 +494,7 @@ public class SweeperTaskModel implements IMoGoSweeperFutianCloudTaskListener, IM } private static String format(double value) { - BigDecimal bd = new BigDecimal(value); + BigDecimal bd = BigDecimal.valueOf(value); bd = bd.setScale(2, RoundingMode.HALF_UP); return bd.toString(); } @@ -688,18 +676,18 @@ public class SweeperTaskModel implements IMoGoSweeperFutianCloudTaskListener, IM if (mControllerStatusCallback != null) { mControllerStatusCallback.onAutopilotState(state); } - switch (state) { - case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_DISABLE://不可自动驾驶 - break; - case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_ENABLE://人工驾驶 - break; - case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_RUNNING://自动驾驶中 - break; - case IMoGoAutopilotStatusListener.STATUS_PARALLEL_DRIVING://平行驾驶 - break; - default: - break; - } +// switch (state) { +// case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_DISABLE://不可自动驾驶 +// break; +// case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_ENABLE://人工驾驶 +// break; +// case IMoGoAutopilotStatusListener.STATUS_AUTOPILOT_RUNNING://自动驾驶中 +// break; +// case IMoGoAutopilotStatusListener.STATUS_PARALLEL_DRIVING://平行驾驶 +// break; +// default: +// break; +// } } @Override diff --git a/OCH/sweeper/sweeper/build.gradle b/OCH/sweeper/sweeper/build.gradle index 499a56f6dc..1471267780 100644 --- a/OCH/sweeper/sweeper/build.gradle +++ b/OCH/sweeper/sweeper/build.gradle @@ -62,6 +62,9 @@ dependencies { implementation project(":OCH:mogo-och-common-module") compileOnly project(":libraries:mogo-map") + androidTestImplementation rootProject.ext.dependencies.androidxjunit + testImplementation rootProject.ext.dependencies.junit + } apply from: new File(rootProject.rootDir, "gradle/upload.gradle").toString() \ No newline at end of file diff --git a/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/SweeperProvider.java b/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/SweeperProvider.java index ac2436d4f6..6f14326a7c 100644 --- a/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/SweeperProvider.java +++ b/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/SweeperProvider.java @@ -36,14 +36,14 @@ public class SweeperProvider implements IMogoOCH { FragmentManager supportFragmentManager = activity.getSupportFragmentManager(); if (sweeperFragment == null) { CallerLogger.d(TAG, "准备add fragment======"); - Fragment fragmentByTag = supportFragmentManager.findFragmentByTag(sweeperFragment.TAG); + Fragment fragmentByTag = supportFragmentManager.findFragmentByTag(SweeperFragment.TAG); if (fragmentByTag instanceof SweeperFragment) { sweeperFragment = (SweeperFragment) fragmentByTag; } else { sweeperFragment = new SweeperFragment(); } if(!sweeperFragment.isAdded()) { - supportFragmentManager.beginTransaction().add(containerId, sweeperFragment, sweeperFragment.TAG).commitAllowingStateLoss(); + supportFragmentManager.beginTransaction().add(containerId, sweeperFragment, SweeperFragment.TAG).commitAllowingStateLoss(); } return; } diff --git a/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/fragment/BaseSweeperTabFragment.java b/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/fragment/BaseSweeperTabFragment.java index cb8754febb..e9fc880d3e 100644 --- a/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/fragment/BaseSweeperTabFragment.java +++ b/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/fragment/BaseSweeperTabFragment.java @@ -408,8 +408,8 @@ public abstract class BaseSweeperTabFragment() { - @Override - public void accept(Throwable e) { - if (e instanceof UndeliverableException) { - e = e.getCause(); - CallerLogger.d(M_SWEEPER + TAG, "UndeliverableException"); - } - if ((e instanceof IOException)) {// - // fine, irrelevant network problem or API that throws on cancellation - CallerLogger.d(M_SWEEPER + TAG, "IOException"); - return; - } - if (e instanceof InterruptedException) { - // fine, some blocking code was interrupted by a dispose call - CallerLogger.d(M_SWEEPER + TAG, "InterruptedException"); - return; - } - if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { - // that's likely a bug in the application - CallerLogger.d(M_SWEEPER + TAG, "NullPointerException or IllegalArgumentException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - if (e instanceof IllegalStateException) { - // that's a bug in RxJava or in a custom operator - CallerLogger.d(M_SWEEPER + TAG, "IllegalStateException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - CallerLogger.d(M_SWEEPER + TAG, "Undeliverable exception"); + // the flow or the exception has nowhere to go to begin with + RxJavaPlugins.setErrorHandler(e -> { + if (e instanceof UndeliverableException) { + e = e.getCause(); + CallerLogger.d(M_SWEEPER + TAG, "UndeliverableException"); } + if ((e instanceof IOException)) { + // fine, irrelevant network problem or API that throws on cancellation + CallerLogger.d(M_SWEEPER + TAG, "IOException"); + return; + } + if (e instanceof InterruptedException) { + // fine, some blocking code was interrupted by a dispose call + CallerLogger.d(M_SWEEPER + TAG, "InterruptedException"); + return; + } + if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { + // that's likely a bug in the application + CallerLogger.d(M_SWEEPER + TAG, "NullPointerException or IllegalArgumentException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + if (e instanceof IllegalStateException) { + // that's a bug in RxJava or in a custom operator + CallerLogger.d(M_SWEEPER + TAG, "IllegalStateException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + CallerLogger.d(M_SWEEPER + TAG, "Undeliverable exception"); }); } @@ -191,7 +188,7 @@ public class SweeperTaskModel { @Override public void onAutopilotRotting(MessagePad.GlobalPathResp routeList) { - if (null != routeList && routeList.getWayPointsList()!=null&&routeList.getWayPointsList().size() > 0) { + if (null != routeList && routeList.getWayPointsList().size() > 0) { if (mCurrentSubTaskDetail.getLineId() != mLineId) {//判断是否同一条路线 mLineId = mCurrentSubTaskDetail.getLineId(); points.addAll(coordinateConverterWgsToGcjList(mContext, routeList.getWayPointsList())); @@ -316,7 +313,6 @@ public class SweeperTaskModel { } if (SubTaskTypeEnum.MANUAL_DRIVING_SUBTYPE.getCode() == mSubTaskType) {//人工驾驶子任务需要手动跳过,不能自动结束 addCoordinates(gnssInfo); - return; } //子任务完成的围栏判断 子任务正在执行中,还未到达子任务终点 //20230504 为了避免自车定位提前结束任务导致的溜车问题,这里删除自车自动触发到站 @@ -365,7 +361,6 @@ public class SweeperTaskModel { isAutopilotSubTaskArriveEndSite = true; //到达子任务终点 结束子任务 subTaskEnd(mIsFirstSubtask, mIsLastSubtask, mSubTaskId); //无自动驾驶到终点信息传null - return; } } @@ -393,10 +388,6 @@ public class SweeperTaskModel { firstStartAutopilot++; triggerStartServiceEvent(isRestart, false); AutopilotControlParameters parameters = initAutopilotControlParameters(); - if (null == parameters) { - CallerLogger.e(M_SWEEPER + TAG, "行程日志-AutopilotControlParameters is empty."); - return; - } CallerAutoPilotControlManager.INSTANCE.startAutoPilot(parameters); CallerLogger.d(M_SWEEPER + TAG, "行程日志-开启自动驾驶====" + GsonUtil.jsonFromObject(parameters) + " startLatLon=" + parameters.startName + ",endLatLon=" + parameters.endName + @@ -496,10 +487,6 @@ public class SweeperTaskModel { private void updateAutopilotControlParameters() { AutopilotControlParameters parameters = initAutopilotControlParameters(); - if (null == parameters) { - CallerLogger.e(M_SWEEPER + TAG, "AutopilotControlParameters is empty."); - return; - } CallerLogger.d(M_SWEEPER + TAG, "AutopilotControlParameters" + GsonUtil.jsonFromObject(parameters)); CallerLogger.d(M_SWEEPER + TAG, "AutopilotControlParameters is update."); CallerAutoPilotStatusListenerManager.INSTANCE.updateAutopilotControlParameters(parameters); diff --git a/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/view/BusArcView.java b/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/view/BusArcView.java index d559214b15..04fa056c2f 100644 --- a/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/view/BusArcView.java +++ b/OCH/sweeper/sweeper/src/main/java/com/mogo/och/sweeper/view/BusArcView.java @@ -30,7 +30,7 @@ public class BusArcView extends View { //圆弧颜色 private int mArcColor; //圆弧的画笔的宽度 - private float mStrokeWith = getResources().getDimension(R.dimen.sweeper_ext_arcView_stroke_with); + private final float mStrokeWith = getResources().getDimension(R.dimen.sweeper_ext_arcView_stroke_with); //文字描述的paint private Paint mTextPaint; @@ -39,9 +39,9 @@ public class BusArcView extends View { //当前数据 private int currentValue; //最大数据 - private int maxValue = 240; + private final int maxValue = 240; //圆弧背景的开始和结束间的夹角大小 - private float mAngle = 270; + private final float mAngle = 270; //上次绘制圆弧夹角 private float lastAngle = 0; @@ -75,13 +75,13 @@ public class BusArcView extends View { mTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); //绘制中心的数值 mTextPaint.getTextBounds(mValue, 0, mValue.length(), mRect); - canvas.drawText(mValue, getWidth() / 2, getHeight() / 2 + mRect.height() / 2 - 10, mTextPaint); + canvas.drawText(mValue, getWidth() / 2.0f, getHeight() / 2.0f + mRect.height() / 2.0f - 10, mTextPaint); mTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); //绘制中心文字描述 mTextPaint.setTextSize(getResources().getDimension(R.dimen.sweeper_ext_arcView_des_text_size)); mTextPaint.getTextBounds(mDes, 0, mDes.length(), mRect); - canvas.drawText(mDes, getWidth() / 2, getHeight() * 17 / 20 + mRect.height() / 2, mTextPaint); + canvas.drawText(mDes, getWidth() / 2.0f, getHeight() * 17.0f / 20.0f + mRect.height() / 2.0f, mTextPaint); } private void drawArc(Canvas canvas) { @@ -135,13 +135,10 @@ public class BusArcView extends View { ValueAnimator progressAnimator = ValueAnimator.ofFloat(startAngle, currentAngle); progressAnimator.setDuration(time); progressAnimator.setTarget(mIncludedAngle); - progressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { - @Override - public void onAnimationUpdate(ValueAnimator animation) { - mIncludedAngle = (float) animation.getAnimatedValue(); - //重新绘制,不然不会出现效果 - postInvalidate(); - } + progressAnimator.addUpdateListener(animation -> { + mIncludedAngle = (float) animation.getAnimatedValue(); + //重新绘制,不然不会出现效果 + postInvalidate(); }); //开始执行动画 progressAnimator.start(); diff --git a/OCH/taxi/driver/src/main/AndroidManifest.xml b/OCH/taxi/driver/src/main/AndroidManifest.xml index fb42392054..ae926fbcd8 100644 --- a/OCH/taxi/driver/src/main/AndroidManifest.xml +++ b/OCH/taxi/driver/src/main/AndroidManifest.xml @@ -1,5 +1,2 @@ - - - / + \ No newline at end of file diff --git a/OCH/taxi/driver/src/main/java/com/mogo/och/taxi/model/TaxiModel.java b/OCH/taxi/driver/src/main/java/com/mogo/och/taxi/model/TaxiModel.java index 23306f26dd..b2ce0b60f2 100644 --- a/OCH/taxi/driver/src/main/java/com/mogo/och/taxi/model/TaxiModel.java +++ b/OCH/taxi/driver/src/main/java/com/mogo/och/taxi/model/TaxiModel.java @@ -5,6 +5,8 @@ import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_SOURCE_ADA import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_TYPE_SOCKET_AUTOPILOT; import static com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant.M_TAXI; +import static java.util.Collections.emptyList; + import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; @@ -123,8 +125,8 @@ public class TaxiModel { private volatile String mPrevOrderNo = ""; //前一次的新到单id(当次和前一次orderId相同时,本次不再弹出) private volatile OrderQueryRespBean.Result mNewBookingOrder; //新到待抢预约单 private volatile OrderQueryRespBean.Result mCurrentOCHOrder; //当前订单 - private volatile List mInServiceList = Collections.emptyList(); //进行中订单 - private volatile List mWaitServiceList = Collections.emptyList(); //待服务订单 + private List mInServiceList = Collections.synchronizedList(emptyList()); //进行中订单 + private volatile List mWaitServiceList = emptyList(); //待服务订单 private ITaxiADASStatusCallback mADASStatusCallback; //Model->Presenter:自动驾驶状态相关 private ITaxiCarOperationalCallback mCarOperationalCallback; //Model->Presenter:登录状态和司机今日接单状态 @@ -135,7 +137,7 @@ public class TaxiModel { private volatile boolean isRestartAutopilot = false; private final List mRoutePoints = new ArrayList<>(); - private int mPreRouteIndex = 0; + private final int mPreRouteIndex = 0; private double mLongitude, mLatitude; private MogoLocation mLocation = null; @@ -180,37 +182,34 @@ public class TaxiModel { //2022.1.28 // 调用Disposable.dispose() 时候会出现InterruptedException 导致出现崩溃 // The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the excTeption has nowhere to go to begin with - RxJavaPlugins.setErrorHandler(new Consumer() { - @Override - public void accept(Throwable e) { - if (e instanceof UndeliverableException) { - e = e.getCause(); - CallerLogger.d(M_TAXI + TAG, "UndeliverableException"); - } - if ((e instanceof IOException)) {// - // fine, irrelevant network problem or API that throws on cancellation - CallerLogger.d(M_TAXI + TAG, "IOException"); - return; - } - if (e instanceof InterruptedException) { - // fine, some blocking code was interrupted by a dispose call - CallerLogger.d(M_TAXI + TAG, "InterruptedException"); - return; - } - if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { - // that's likely a bug in the application - CallerLogger.d(M_TAXI + TAG, "NullPointerException or IllegalArgumentException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - if (e instanceof IllegalStateException) { - // that's a bug in RxJava or in a custom operator - CallerLogger.d(M_TAXI + TAG, "IllegalStateException"); - Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); - return; - } - CallerLogger.d(M_TAXI + TAG, "Undeliverable exception"); + RxJavaPlugins.setErrorHandler(e -> { + if (e instanceof UndeliverableException) { + e = e.getCause(); + CallerLogger.d(M_TAXI + TAG, "UndeliverableException"); } + if ((e instanceof IOException)) {// + // fine, irrelevant network problem or API that throws on cancellation + CallerLogger.d(M_TAXI + TAG, "IOException"); + return; + } + if (e instanceof InterruptedException) { + // fine, some blocking code was interrupted by a dispose call + CallerLogger.d(M_TAXI + TAG, "InterruptedException"); + return; + } + if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { + // that's likely a bug in the application + CallerLogger.d(M_TAXI + TAG, "NullPointerException or IllegalArgumentException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + if (e instanceof IllegalStateException) { + // that's a bug in RxJava or in a custom operator + CallerLogger.d(M_TAXI + TAG, "IllegalStateException"); + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); + return; + } + CallerLogger.d(M_TAXI + TAG, "Undeliverable exception"); }); } @@ -1595,8 +1594,8 @@ public class TaxiModel { /** * 上报订单剩余里程和时间 单位:KM, M, 单位:秒 * - * @param lastSumLength - * @param duration + * @param lastSumLength 上报订单剩余里程 + * @param duration 上报订单剩余时间 */ public void reportOrderRemain(long lastSumLength, long duration) {// 米/秒 if (mCurrentOCHOrder == null) return; @@ -1737,18 +1736,15 @@ public class TaxiModel { mOrderStatusCallback.onNaviToEnd(false, isShow); } } else {//若直接要显示导航地图则直接导航, 若不是则2s后若无轨迹数据使用高德导航 - if (isShow && mRoutePoints.size() == 0 && mOrderStatusCallback != null) { + if (isShow && mOrderStatusCallback != null) { mOrderStatusCallback.onNaviToEnd(true, true); } else { - UiThreadHandler.postDelayed(new Runnable() { - @Override - public void run() { - if (mRoutePoints.size() == 0 && mOrderStatusCallback != null) { - mOrderStatusCallback.onNaviToEnd(true, false); - } + UiThreadHandler.postDelayed(() -> { + if (mRoutePoints.size() == 0 && mOrderStatusCallback != null) { + mOrderStatusCallback.onNaviToEnd(true, false); } - }, 2000l); + }, 2000L); } } diff --git a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/ui/arrived/RightRearCamView.kt b/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/ui/arrived/RightRearCamView.kt index 336357d774..655a132350 100644 --- a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/ui/arrived/RightRearCamView.kt +++ b/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/ui/arrived/RightRearCamView.kt @@ -5,7 +5,6 @@ import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable import android.util.AttributeSet -import android.util.Log import android.view.LayoutInflater import androidx.constraintlayout.widget.ConstraintLayout import com.mogo.eagle.core.function.api.autopilot.IMoGoBackCameraVideoListener @@ -128,7 +127,7 @@ class RightRearCamView : ConstraintLayout , IMoGoBackCameraVideoListener, private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int { val width = options.outWidth val height = options.outHeight - Log.i(TAG, "calculateInSampleSize: out width and height is $width height $height") + d(SceneConstant.M_TAXI_P + TAG, "calculateInSampleSize: out width and height is $width height $height") var inSampleWidth = 1 if (height > reqHeight || width > reqWidth) { val halfHeight = height / 2 diff --git a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/DiskLruCache.java b/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/DiskLruCache.java index ce78bbf2d5..e69de29bb2 100644 --- a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/DiskLruCache.java +++ b/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/DiskLruCache.java @@ -1,974 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * 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.mogo.och.taxi.passenger.utils.blur; - -import java.io.BufferedWriter; -import java.io.Closeable; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * A cache that uses a bounded amount of space on a filesystem. Each cache - * entry has a string key and a fixed number of values. Each key must match - * the regex [a-z0-9_-]{1,64}. Values are byte sequences, - * accessible as streams or files. Each value must be between {@code 0} and - * {@code Integer.MAX_VALUE} bytes in length. - * - *

The cache stores its data in a directory on the filesystem. This - * directory must be exclusive to the cache; the cache may delete or overwrite - * files from its directory. It is an error for multiple processes to use the - * same cache directory at the same time. - * - *

This cache limits the number of bytes that it will store on the - * filesystem. When the number of stored bytes exceeds the limit, the cache will - * remove entries in the background until the limit is satisfied. The limit is - * not strict: the cache may temporarily exceed it while waiting for files to be - * deleted. The limit does not include filesystem overhead or the cache - * journal so space-sensitive applications should set a conservative limit. - * - *

Clients call {@link #edit} to create or update the values of an entry. An - * entry may have only one editor at one time; if a value is not available to be - * edited then {@link #edit} will return null. - *

    - *
  • When an entry is being created it is necessary to - * supply a full set of values; the empty value should be used as a - * placeholder if necessary. - *
  • When an entry is being edited, it is not necessary - * to supply data for every value; values default to their previous - * value. - *
- * Every {@link #edit} call must be matched by a call to {@link Editor#commit} - * or {@link Editor#abort}. Committing is atomic: a read observes the full set - * of values as they were before or after the commit, but never a mix of values. - * - *

Clients call {@link #get} to read a snapshot of an entry. The read will - * observe the value at the time that {@link #get} was called. Updates and - * removals after the call do not impact ongoing reads. - * - *

This class is tolerant of some I/O errors. If files are missing from the - * filesystem, the corresponding entries will be dropped from the cache. If - * an error occurs while writing a cache value, the edit will fail silently. - * Callers should handle other problems by catching {@code IOException} and - * responding appropriately. - */ -final class DiskLruCache implements Closeable { - static final String JOURNAL_FILE = "journal"; - static final String JOURNAL_FILE_TEMP = "journal.tmp"; - static final String JOURNAL_FILE_BACKUP = "journal.bkp"; - static final String MAGIC = "libcore.io.DiskLruCache"; - static final String VERSION_1 = "1"; - static final long ANY_SEQUENCE_NUMBER = -1; - static final Pattern LEGAL_KEY_PATTERN = Pattern.compile("[a-z0-9_-]{1,64}"); - private static final String CLEAN = "CLEAN"; - private static final String DIRTY = "DIRTY"; - private static final String REMOVE = "REMOVE"; - private static final String READ = "READ"; - - /* - * This cache uses a journal file named "journal". A typical journal file - * looks like this: - * libcore.io.DiskLruCache - * 1 - * 100 - * 2 - * - * CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054 - * DIRTY 335c4c6028171cfddfbaae1a9c313c52 - * CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342 - * REMOVE 335c4c6028171cfddfbaae1a9c313c52 - * DIRTY 1ab96a171faeeee38496d8b330771a7a - * CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234 - * READ 335c4c6028171cfddfbaae1a9c313c52 - * READ 3400330d1dfc7f3f7f4b8d4d803dfcf6 - * - * The first five lines of the journal form its header. They are the - * constant string "libcore.io.DiskLruCache", the disk cache's version, - * the application's version, the value count, and a blank line. - * - * Each of the subsequent lines in the file is a record of the state of a - * cache entry. Each line contains space-separated values: a state, a key, - * and optional state-specific values. - * o DIRTY lines track that an entry is actively being created or updated. - * Every successful DIRTY action should be followed by a CLEAN or REMOVE - * action. DIRTY lines without a matching CLEAN or REMOVE indicate that - * temporary files may need to be deleted. - * o CLEAN lines track a cache entry that has been successfully published - * and may be read. A publish line is followed by the lengths of each of - * its values. - * o READ lines track accesses for LRU. - * o REMOVE lines track entries that have been deleted. - * - * The journal file is appended to as cache operations occur. The journal may - * occasionally be compacted by dropping redundant lines. A temporary file named - * "journal.tmp" will be used during compaction; that file should be deleted if - * it exists when the cache is opened. - */ - - private final File directory; - private final File journalFile; - private final File journalFileTmp; - private final File journalFileBackup; - private final int appVersion; - private long maxSize; - private int maxFileCount; - private final int valueCount; - private long size = 0; - private int fileCount = 0; - private Writer journalWriter; - private final LinkedHashMap lruEntries = - new LinkedHashMap(0, 0.75f, true); - private int redundantOpCount; - - /** - * To differentiate between old and current snapshots, each entry is given - * a sequence number each time an edit is committed. A snapshot is stale if - * its sequence number is not equal to its entry's sequence number. - */ - private long nextSequenceNumber = 0; - - /** This cache uses a single background thread to evict entries. */ - final ThreadPoolExecutor executorService = - new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue()); - private final Callable cleanupCallable = new Callable() { - public Void call() throws Exception { - synchronized (DiskLruCache.this) { - if (journalWriter == null) { - return null; // Closed. - } - trimToSize(); - trimToFileCount(); - if (journalRebuildRequired()) { - rebuildJournal(); - redundantOpCount = 0; - } - } - return null; - } - }; - - private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize, int maxFileCount) { - this.directory = directory; - this.appVersion = appVersion; - this.journalFile = new File(directory, JOURNAL_FILE); - this.journalFileTmp = new File(directory, JOURNAL_FILE_TEMP); - this.journalFileBackup = new File(directory, JOURNAL_FILE_BACKUP); - this.valueCount = valueCount; - this.maxSize = maxSize; - this.maxFileCount = maxFileCount; - } - - /** - * Opens the cache in {@code directory}, creating a cache if none exists - * there. - * - * @param directory a writable directory - * @param valueCount the number of values per cache entry. Must be positive. - * @param maxSize the maximum number of bytes this cache should use to store - * @param maxFileCount the maximum file count this cache should store - * @throws IOException if reading or writing the cache directory fails - */ - public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize, int maxFileCount) - throws IOException { - if (maxSize <= 0) { - throw new IllegalArgumentException("maxSize <= 0"); - } - if (maxFileCount <= 0) { - throw new IllegalArgumentException("maxFileCount <= 0"); - } - if (valueCount <= 0) { - throw new IllegalArgumentException("valueCount <= 0"); - } - - // If a bkp file exists, use it instead. - File backupFile = new File(directory, JOURNAL_FILE_BACKUP); - if (backupFile.exists()) { - File journalFile = new File(directory, JOURNAL_FILE); - // If journal file also exists just delete backup file. - if (journalFile.exists()) { - backupFile.delete(); - } else { - renameTo(backupFile, journalFile, false); - } - } - - // Prefer to pick up where we left off. - DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize, maxFileCount); - if (cache.journalFile.exists()) { - try { - cache.readJournal(); - cache.processJournal(); - cache.journalWriter = new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(cache.journalFile, true), Util.US_ASCII)); - return cache; - } catch (IOException journalIsCorrupt) { - System.out - .println("DiskLruCache " - + directory - + " is corrupt: " - + journalIsCorrupt.getMessage() - + ", removing"); - cache.delete(); - } - } - - // Create a new empty cache. - directory.mkdirs(); - cache = new DiskLruCache(directory, appVersion, valueCount, maxSize, maxFileCount); - cache.rebuildJournal(); - return cache; - } - - private void readJournal() throws IOException { - StrictLineReader reader = new StrictLineReader(new FileInputStream(journalFile), Util.US_ASCII); - try { - String magic = reader.readLine(); - String version = reader.readLine(); - String appVersionString = reader.readLine(); - String valueCountString = reader.readLine(); - String blank = reader.readLine(); - if (!MAGIC.equals(magic) - || !VERSION_1.equals(version) - || !Integer.toString(appVersion).equals(appVersionString) - || !Integer.toString(valueCount).equals(valueCountString) - || !"".equals(blank)) { - throw new IOException("unexpected journal header: [" + magic + ", " + version + ", " - + valueCountString + ", " + blank + "]"); - } - - int lineCount = 0; - while (true) { - try { - readJournalLine(reader.readLine()); - lineCount++; - } catch (EOFException endOfJournal) { - break; - } - } - redundantOpCount = lineCount - lruEntries.size(); - } finally { - Util.closeQuietly(reader); - } - } - - private void readJournalLine(String line) throws IOException { - int firstSpace = line.indexOf(' '); - if (firstSpace == -1) { - throw new IOException("unexpected journal line: " + line); - } - - int keyBegin = firstSpace + 1; - int secondSpace = line.indexOf(' ', keyBegin); - final String key; - if (secondSpace == -1) { - key = line.substring(keyBegin); - if (firstSpace == REMOVE.length() && line.startsWith(REMOVE)) { - lruEntries.remove(key); - return; - } - } else { - key = line.substring(keyBegin, secondSpace); - } - - Entry entry = lruEntries.get(key); - if (entry == null) { - entry = new Entry(key); - lruEntries.put(key, entry); - } - - if (secondSpace != -1 && firstSpace == CLEAN.length() && line.startsWith(CLEAN)) { - String[] parts = line.substring(secondSpace + 1).split(" "); - entry.readable = true; - entry.currentEditor = null; - entry.setLengths(parts); - } else if (secondSpace == -1 && firstSpace == DIRTY.length() && line.startsWith(DIRTY)) { - entry.currentEditor = new Editor(entry); - } else if (secondSpace == -1 && firstSpace == READ.length() && line.startsWith(READ)) { - // This work was already done by calling lruEntries.get(). - } else { - throw new IOException("unexpected journal line: " + line); - } - } - - /** - * Computes the initial size and collects garbage as a part of opening the - * cache. Dirty entries are assumed to be inconsistent and will be deleted. - */ - private void processJournal() throws IOException { - deleteIfExists(journalFileTmp); - for (Iterator i = lruEntries.values().iterator(); i.hasNext(); ) { - Entry entry = i.next(); - if (entry.currentEditor == null) { - for (int t = 0; t < valueCount; t++) { - size += entry.lengths[t]; - fileCount++; - } - } else { - entry.currentEditor = null; - for (int t = 0; t < valueCount; t++) { - deleteIfExists(entry.getCleanFile(t)); - deleteIfExists(entry.getDirtyFile(t)); - } - i.remove(); - } - } - } - - /** - * Creates a new journal that omits redundant information. This replaces the - * current journal if it exists. - */ - private synchronized void rebuildJournal() throws IOException { - if (journalWriter != null) { - journalWriter.close(); - } - - Writer writer = new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII)); - try { - writer.write(MAGIC); - writer.write("\n"); - writer.write(VERSION_1); - writer.write("\n"); - writer.write(Integer.toString(appVersion)); - writer.write("\n"); - writer.write(Integer.toString(valueCount)); - writer.write("\n"); - writer.write("\n"); - - for (Entry entry : lruEntries.values()) { - if (entry.currentEditor != null) { - writer.write(DIRTY + ' ' + entry.key + '\n'); - } else { - writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); - } - } - } finally { - writer.close(); - } - - if (journalFile.exists()) { - renameTo(journalFile, journalFileBackup, true); - } - renameTo(journalFileTmp, journalFile, false); - journalFileBackup.delete(); - - journalWriter = new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(journalFile, true), Util.US_ASCII)); - } - - private static void deleteIfExists(File file) throws IOException { - if (file.exists() && !file.delete()) { - throw new IOException(); - } - } - - private static void renameTo(File from, File to, boolean deleteDestination) throws IOException { - if (deleteDestination) { - deleteIfExists(to); - } - if (!from.renameTo(to)) { - throw new IOException(); - } - } - - /** - * Returns a snapshot of the entry named {@code key}, or null if it doesn't - * exist is not currently readable. If a value is returned, it is moved to - * the head of the LRU queue. - */ - public synchronized Snapshot get(String key) throws IOException { - checkNotClosed(); - validateKey(key); - Entry entry = lruEntries.get(key); - if (entry == null) { - return null; - } - - if (!entry.readable) { - return null; - } - - // Open all streams eagerly to guarantee that we see a single published - // snapshot. If we opened streams lazily then the streams could come - // from different edits. - File[] files = new File[valueCount]; - InputStream[] ins = new InputStream[valueCount]; - try { - File file; - for (int i = 0; i < valueCount; i++) { - file = entry.getCleanFile(i); - files[i] = file; - ins[i] = new FileInputStream(file); - } - } catch (FileNotFoundException e) { - // A file must have been deleted manually! - for (int i = 0; i < valueCount; i++) { - if (ins[i] != null) { - Util.closeQuietly(ins[i]); - } else { - break; - } - } - return null; - } - - redundantOpCount++; - journalWriter.append(READ + ' ' + key + '\n'); - if (journalRebuildRequired()) { - executorService.submit(cleanupCallable); - } - - return new Snapshot(key, entry.sequenceNumber, files, ins, entry.lengths); - } - - /** - * Returns an editor for the entry named {@code key}, or null if another - * edit is in progress. - */ - public Editor edit(String key) throws IOException { - return edit(key, ANY_SEQUENCE_NUMBER); - } - - private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException { - checkNotClosed(); - validateKey(key); - Entry entry = lruEntries.get(key); - if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null - || entry.sequenceNumber != expectedSequenceNumber)) { - return null; // Snapshot is stale. - } - if (entry == null) { - entry = new Entry(key); - lruEntries.put(key, entry); - } else if (entry.currentEditor != null) { - return null; // Another edit is in progress. - } - - Editor editor = new Editor(entry); - entry.currentEditor = editor; - - // Flush the journal before creating files to prevent file leaks. - journalWriter.write(DIRTY + ' ' + key + '\n'); - journalWriter.flush(); - return editor; - } - - /** Returns the directory where this cache stores its data. */ - public File getDirectory() { - return directory; - } - - /** - * Returns the maximum number of bytes that this cache should use to store - * its data. - */ - public synchronized long getMaxSize() { - return maxSize; - } - - /** Returns the maximum number of files that this cache should store */ - public synchronized int getMaxFileCount() { - return maxFileCount; - } - - /** - * Changes the maximum number of bytes the cache can store and queues a job - * to trim the existing store, if necessary. - */ - public synchronized void setMaxSize(long maxSize) { - this.maxSize = maxSize; - executorService.submit(cleanupCallable); - } - - /** - * Returns the number of bytes currently being used to store the values in - * this cache. This may be greater than the max size if a background - * deletion is pending. - */ - public synchronized long size() { - return size; - } - - /** - * Returns the number of files currently being used to store the values in - * this cache. This may be greater than the max file count if a background - * deletion is pending. - */ - public synchronized long fileCount() { - return fileCount; - } - - private synchronized void completeEdit(Editor editor, boolean success) throws IOException { - Entry entry = editor.entry; - if (entry.currentEditor != editor) { - throw new IllegalStateException(); - } - - // If this edit is creating the entry for the first time, every index must have a value. - if (success && !entry.readable) { - for (int i = 0; i < valueCount; i++) { - if (!editor.written[i]) { - editor.abort(); - throw new IllegalStateException("Newly created entry didn't create value for index " + i); - } - if (!entry.getDirtyFile(i).exists()) { - editor.abort(); - return; - } - } - } - - for (int i = 0; i < valueCount; i++) { - File dirty = entry.getDirtyFile(i); - if (success) { - if (dirty.exists()) { - File clean = entry.getCleanFile(i); - dirty.renameTo(clean); - long oldLength = entry.lengths[i]; - long newLength = clean.length(); - entry.lengths[i] = newLength; - size = size - oldLength + newLength; - fileCount++; - } - } else { - deleteIfExists(dirty); - } - } - - redundantOpCount++; - entry.currentEditor = null; - if (entry.readable | success) { - entry.readable = true; - journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); - if (success) { - entry.sequenceNumber = nextSequenceNumber++; - } - } else { - lruEntries.remove(entry.key); - journalWriter.write(REMOVE + ' ' + entry.key + '\n'); - } - journalWriter.flush(); - - if (size > maxSize || fileCount > maxFileCount || journalRebuildRequired()) { - executorService.submit(cleanupCallable); - } - } - - /** - * We only rebuild the journal when it will halve the size of the journal - * and eliminate at least 2000 ops. - */ - private boolean journalRebuildRequired() { - final int redundantOpCompactThreshold = 2000; - return redundantOpCount >= redundantOpCompactThreshold // - && redundantOpCount >= lruEntries.size(); - } - - /** - * Drops the entry for {@code key} if it exists and can be removed. Entries - * actively being edited cannot be removed. - * - * @return true if an entry was removed. - */ - public synchronized boolean remove(String key) throws IOException { - checkNotClosed(); - validateKey(key); - Entry entry = lruEntries.get(key); - if (entry == null || entry.currentEditor != null) { - return false; - } - - for (int i = 0; i < valueCount; i++) { - File file = entry.getCleanFile(i); - if (file.exists() && !file.delete()) { - throw new IOException("failed to delete " + file); - } - size -= entry.lengths[i]; - fileCount--; - entry.lengths[i] = 0; - } - - redundantOpCount++; - journalWriter.append(REMOVE + ' ' + key + '\n'); - lruEntries.remove(key); - - if (journalRebuildRequired()) { - executorService.submit(cleanupCallable); - } - - return true; - } - - /** Returns true if this cache has been closed. */ - public synchronized boolean isClosed() { - return journalWriter == null; - } - - private void checkNotClosed() { - if (journalWriter == null) { - throw new IllegalStateException("cache is closed"); - } - } - - /** Force buffered operations to the filesystem. */ - public synchronized void flush() throws IOException { - checkNotClosed(); - trimToSize(); - trimToFileCount(); - journalWriter.flush(); - } - - /** Closes this cache. Stored values will remain on the filesystem. */ - public synchronized void close() throws IOException { - if (journalWriter == null) { - return; // Already closed. - } - for (Entry entry : new ArrayList(lruEntries.values())) { - if (entry.currentEditor != null) { - entry.currentEditor.abort(); - } - } - trimToSize(); - trimToFileCount(); - journalWriter.close(); - journalWriter = null; - } - - private void trimToSize() throws IOException { - while (size > maxSize) { - Map.Entry toEvict = lruEntries.entrySet().iterator().next(); - remove(toEvict.getKey()); - } - } - - private void trimToFileCount() throws IOException { - while (fileCount > maxFileCount) { - Map.Entry toEvict = lruEntries.entrySet().iterator().next(); - remove(toEvict.getKey()); - } - } - - /** - * Closes the cache and deletes all of its stored values. This will delete - * all files in the cache directory including files that weren't created by - * the cache. - */ - public void delete() throws IOException { - close(); - Util.deleteContents(directory); - } - - private void validateKey(String key) { - Matcher matcher = LEGAL_KEY_PATTERN.matcher(key); - if (!matcher.matches()) { - throw new IllegalArgumentException("keys must match regex [a-z0-9_-]{1,64}: " + key); - } - } - - private static String inputStreamToString(InputStream in) throws IOException { - return Util.readFully(new InputStreamReader(in, Util.UTF_8)); - } - - /** A snapshot of the values for an entry. */ - public final class Snapshot implements Closeable { - private final String key; - private final long sequenceNumber; - private File[] files; - private final InputStream[] ins; - private final long[] lengths; - - private Snapshot(String key, long sequenceNumber, File[] files, InputStream[] ins, long[] lengths) { - this.key = key; - this.sequenceNumber = sequenceNumber; - this.files = files; - this.ins = ins; - this.lengths = lengths; - } - - /** - * Returns an editor for this snapshot's entry, or null if either the - * entry has changed since this snapshot was created or if another edit - * is in progress. - */ - public Editor edit() throws IOException { - return DiskLruCache.this.edit(key, sequenceNumber); - } - - /** Returns file with the value for {@code index}. */ - public File getFile(int index) { - return files[index]; - } - - /** Returns the unbuffered stream with the value for {@code index}. */ - public InputStream getInputStream(int index) { - return ins[index]; - } - - /** Returns the string value for {@code index}. */ - public String getString(int index) throws IOException { - return inputStreamToString(getInputStream(index)); - } - - /** Returns the byte length of the value for {@code index}. */ - public long getLength(int index) { - return lengths[index]; - } - - public void close() { - for (InputStream in : ins) { - Util.closeQuietly(in); - } - } - } - - private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() { - @Override - public void write(int b) throws IOException { - // Eat all writes silently. Nom nom. - } - }; - - /** Edits the values for an entry. */ - public final class Editor { - private final Entry entry; - private final boolean[] written; - private boolean hasErrors; - private boolean committed; - - private Editor(Entry entry) { - this.entry = entry; - this.written = (entry.readable) ? null : new boolean[valueCount]; - } - - /** - * Returns an unbuffered input stream to read the last committed value, - * or null if no value has been committed. - */ - public InputStream newInputStream(int index) throws IOException { - synchronized (DiskLruCache.this) { - if (entry.currentEditor != this) { - throw new IllegalStateException(); - } - if (!entry.readable) { - return null; - } - try { - return new FileInputStream(entry.getCleanFile(index)); - } catch (FileNotFoundException e) { - return null; - } - } - } - - /** - * Returns the last committed value as a string, or null if no value - * has been committed. - */ - public String getString(int index) throws IOException { - InputStream in = newInputStream(index); - return in != null ? inputStreamToString(in) : null; - } - - /** - * Returns a new unbuffered output stream to write the value at - * {@code index}. If the underlying output stream encounters errors - * when writing to the filesystem, this edit will be aborted when - * {@link #commit} is called. The returned output stream does not throw - * IOExceptions. - */ - public OutputStream newOutputStream(int index) throws IOException { - synchronized (DiskLruCache.this) { - if (entry.currentEditor != this) { - throw new IllegalStateException(); - } - if (!entry.readable) { - written[index] = true; - } - File dirtyFile = entry.getDirtyFile(index); - FileOutputStream outputStream; - try { - outputStream = new FileOutputStream(dirtyFile); - } catch (FileNotFoundException e) { - // Attempt to recreate the cache directory. - directory.mkdirs(); - try { - outputStream = new FileOutputStream(dirtyFile); - } catch (FileNotFoundException e2) { - // We are unable to recover. Silently eat the writes. - return NULL_OUTPUT_STREAM; - } - } - return new FaultHidingOutputStream(outputStream); - } - } - - /** Sets the value at {@code index} to {@code value}. */ - public void set(int index, String value) throws IOException { - Writer writer = null; - try { - writer = new OutputStreamWriter(newOutputStream(index), Util.UTF_8); - writer.write(value); - } finally { - Util.closeQuietly(writer); - } - } - - /** - * Commits this edit so it is visible to readers. This releases the - * edit lock so another edit may be started on the same key. - */ - public void commit() throws IOException { - if (hasErrors) { - completeEdit(this, false); - remove(entry.key); // The previous entry is stale. - } else { - completeEdit(this, true); - } - committed = true; - } - - /** - * Aborts this edit. This releases the edit lock so another edit may be - * started on the same key. - */ - public void abort() throws IOException { - completeEdit(this, false); - } - - public void abortUnlessCommitted() { - if (!committed) { - try { - abort(); - } catch (IOException ignored) { - } - } - } - - private class FaultHidingOutputStream extends FilterOutputStream { - private FaultHidingOutputStream(OutputStream out) { - super(out); - } - - @Override public void write(int oneByte) { - try { - out.write(oneByte); - } catch (IOException e) { - hasErrors = true; - } - } - - @Override public void write(byte[] buffer, int offset, int length) { - try { - out.write(buffer, offset, length); - } catch (IOException e) { - hasErrors = true; - } - } - - @Override public void close() { - try { - out.close(); - } catch (IOException e) { - hasErrors = true; - } - } - - @Override public void flush() { - try { - out.flush(); - } catch (IOException e) { - hasErrors = true; - } - } - } - } - - private final class Entry { - private final String key; - - /** Lengths of this entry's files. */ - private final long[] lengths; - - /** True if this entry has ever been published. */ - private boolean readable; - - /** The ongoing edit or null if this entry is not being edited. */ - private Editor currentEditor; - - /** The sequence number of the most recently committed edit to this entry. */ - private long sequenceNumber; - - private Entry(String key) { - this.key = key; - this.lengths = new long[valueCount]; - } - - public String getLengths() throws IOException { - StringBuilder result = new StringBuilder(); - for (long size : lengths) { - result.append(' ').append(size); - } - return result.toString(); - } - - /** Set lengths using decimal numbers like "10123". */ - private void setLengths(String[] strings) throws IOException { - if (strings.length != valueCount) { - throw invalidLengths(strings); - } - - try { - for (int i = 0; i < strings.length; i++) { - lengths[i] = Long.parseLong(strings[i]); - } - } catch (NumberFormatException e) { - throw invalidLengths(strings); - } - } - - private IOException invalidLengths(String[] strings) throws IOException { - throw new IOException("unexpected journal line: " + java.util.Arrays.toString(strings)); - } - - public File getCleanFile(int i) { - return new File(directory, key + i); - } - - public File getDirtyFile(int i) { - return new File(directory, key + i + ".tmp"); - } - } -} diff --git a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/DiskLruCacheManager.java b/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/DiskLruCacheManager.java index 424c5dce56..e69de29bb2 100644 --- a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/DiskLruCacheManager.java +++ b/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/DiskLruCacheManager.java @@ -1,101 +0,0 @@ -package com.mogo.och.taxi.passenger.utils.blur; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.text.TextUtils; - -import java.io.InputStream; -import java.io.OutputStream; -import java.math.BigInteger; -import java.security.MessageDigest; - -/******************************************************************************* - * Description: 用于缓存经过高斯模糊的图片 - * - * Author: Freeman - * - * Date: 2018/9/4 - * - * Copyright: all rights reserved by Freeman. - *******************************************************************************/ -public class DiskLruCacheManager { - - private DiskLruCache diskLruCache; - private static DiskLruCacheManager instance; - - private final int MAX_CACHE_SIZE = 64 * 1024 * 1024; - - private DiskLruCacheManager(Context context) { - try { - diskLruCache = DiskLruCache.open(context.getCacheDir(), 1, 1, - MAX_CACHE_SIZE, Integer.MAX_VALUE); - } catch (Exception e) { - e.printStackTrace(System.err); - } - } - - public static DiskLruCacheManager getInstance(Context context) { - if (instance == null) { - synchronized (DiskLruCacheManager.class) { - if (instance == null) { - instance = new DiskLruCacheManager(context.getApplicationContext()); - } - } - } - - return instance; - } - - public void put(String url, Bitmap bitmap) { - if (TextUtils.isEmpty(url) || bitmap == null || bitmap.isRecycled()) { - return; - } - - try { - DiskLruCache.Editor editor = diskLruCache.edit(getKey(url)); - OutputStream outputStream = editor.newOutputStream(0); - if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)) { - editor.commit(); - } - diskLruCache.flush(); - } catch (Exception e) { - e.printStackTrace(System.err); - } - } - - public Bitmap get(String url) { - try { - DiskLruCache.Snapshot snapshot = diskLruCache.get(getKey(url)); - if (snapshot != null) { - InputStream inputStream = snapshot.getInputStream(0); - return BitmapFactory.decodeStream(inputStream); - } - } catch (Exception e) { - e.printStackTrace(System.err); - } - - return null; - } - - public static String getKey(String url) { - try { - MessageDigest digest = MessageDigest.getInstance("MD5"); - byte[] md5 = digest.digest(url.getBytes()); - BigInteger bigInteger = new BigInteger(1, md5); - return bigInteger.toString(16); - } catch (Exception e) { - e.printStackTrace(System.err); - } - - return null; - } - - public void close() { - try { - diskLruCache.close(); - } catch (Exception e) { - e.printStackTrace(System.err); - } - } -} diff --git a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/FastBlurUtil.java b/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/FastBlurUtil.java deleted file mode 100644 index bab7819ba1..0000000000 --- a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/FastBlurUtil.java +++ /dev/null @@ -1,241 +0,0 @@ -package com.mogo.och.taxi.passenger.utils.blur; - -import android.graphics.Bitmap; - -/** - * Created by jay on 11/7/15. - */ -public class FastBlurUtil { - - public static Bitmap doBlur(Bitmap sentBitmap, int scaleRadius, int radius) { - - // Stack Blur v1.0 from - // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html - // - // Java Author: Mario Klingemann - // http://incubator.quasimondo.com - // created Feburary 29, 2004 - // Android port : Yahel Bouaziz - // http://www.kayenko.com - // ported april 5th, 2012 - - // This is a compromise between Gaussian Blur and Box blur - // It creates much better looking blurs than Box Blur, but is - // 7x faster than my Gaussian Blur implementation. - // - // I called it Stack Blur because this describes best how this - // filter works internally: it creates a kind of moving stack - // of colors whilst scanning through the image. Thereby it - // just has to add one new block of color to the right side - // of the stack and remove the leftmost color. The remaining - // colors on the topmost layer of the stack are either added on - // or reduced by one, depending on if they are on the right or - // on the left side of the stack. - // - // If you are using this algorithm in your code please add - // the following line: - // - // Stack Blur Algorithm by Mario Klingemann - if (scaleRadius > 0) { - sentBitmap = Bitmap.createScaledBitmap(sentBitmap, sentBitmap.getWidth() / scaleRadius, - sentBitmap.getHeight() / scaleRadius, false); - } - Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true); - - if (radius < 1) { - return (null); - } - int w = bitmap.getWidth(); - int h = bitmap.getHeight(); - - int[] pix = new int[w * h]; - bitmap.getPixels(pix, 0, w, 0, 0, w, h); - - int wm = w - 1; - int hm = h - 1; - int wh = w * h; - int div = radius + radius + 1; - - int r[] = new int[wh]; - int g[] = new int[wh]; - int b[] = new int[wh]; - int rsum, gsum, bsum, x, y, i, p, yp, yi, yw; - int vmin[] = new int[Math.max(w, h)]; - - int divsum = (div + 1) >> 1; - divsum *= divsum; - int dv[] = new int[256 * divsum]; - for (i = 0; i < 256 * divsum; i++) { - dv[i] = (i / divsum); - } - - yw = yi = 0; - - int[][] stack = new int[div][3]; - int stackpointer; - int stackstart; - int[] sir; - int rbs; - int r1 = radius + 1; - int routsum, goutsum, boutsum; - int rinsum, ginsum, binsum; - - for (y = 0; y < h; y++) { - rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0; - for (i = -radius; i <= radius; i++) { - p = pix[yi + Math.min(wm, Math.max(i, 0))]; - sir = stack[i + radius]; - sir[0] = (p & 0xff0000) >> 16; - sir[1] = (p & 0x00ff00) >> 8; - sir[2] = (p & 0x0000ff); - rbs = r1 - Math.abs(i); - rsum += sir[0] * rbs; - gsum += sir[1] * rbs; - bsum += sir[2] * rbs; - if (i > 0) { - rinsum += sir[0]; - ginsum += sir[1]; - binsum += sir[2]; - } else { - routsum += sir[0]; - goutsum += sir[1]; - boutsum += sir[2]; - } - } - stackpointer = radius; - - for (x = 0; x < w; x++) { - - r[yi] = dv[rsum]; - g[yi] = dv[gsum]; - b[yi] = dv[bsum]; - - rsum -= routsum; - gsum -= goutsum; - bsum -= boutsum; - - stackstart = stackpointer - radius + div; - sir = stack[stackstart % div]; - - routsum -= sir[0]; - goutsum -= sir[1]; - boutsum -= sir[2]; - - if (y == 0) { - vmin[x] = Math.min(x + radius + 1, wm); - } - p = pix[yw + vmin[x]]; - - sir[0] = (p & 0xff0000) >> 16; - sir[1] = (p & 0x00ff00) >> 8; - sir[2] = (p & 0x0000ff); - - rinsum += sir[0]; - ginsum += sir[1]; - binsum += sir[2]; - - rsum += rinsum; - gsum += ginsum; - bsum += binsum; - - stackpointer = (stackpointer + 1) % div; - sir = stack[(stackpointer) % div]; - - routsum += sir[0]; - goutsum += sir[1]; - boutsum += sir[2]; - - rinsum -= sir[0]; - ginsum -= sir[1]; - binsum -= sir[2]; - - yi++; - } - yw += w; - } - for (x = 0; x < w; x++) { - rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0; - yp = -radius * w; - for (i = -radius; i <= radius; i++) { - yi = Math.max(0, yp) + x; - - sir = stack[i + radius]; - - sir[0] = r[yi]; - sir[1] = g[yi]; - sir[2] = b[yi]; - - rbs = r1 - Math.abs(i); - - rsum += r[yi] * rbs; - gsum += g[yi] * rbs; - bsum += b[yi] * rbs; - - if (i > 0) { - rinsum += sir[0]; - ginsum += sir[1]; - binsum += sir[2]; - } else { - routsum += sir[0]; - goutsum += sir[1]; - boutsum += sir[2]; - } - - if (i < hm) { - yp += w; - } - } - yi = x; - stackpointer = radius; - for (y = 0; y < h; y++) { - // Preserve alpha channel: ( 0xff000000 & pix[yi] ) - pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum]; - - rsum -= routsum; - gsum -= goutsum; - bsum -= boutsum; - - stackstart = stackpointer - radius + div; - sir = stack[stackstart % div]; - - routsum -= sir[0]; - goutsum -= sir[1]; - boutsum -= sir[2]; - - if (x == 0) { - vmin[y] = Math.min(y + r1, hm) * w; - } - p = x + vmin[y]; - - sir[0] = r[p]; - sir[1] = g[p]; - sir[2] = b[p]; - - rinsum += sir[0]; - ginsum += sir[1]; - binsum += sir[2]; - - rsum += rinsum; - gsum += ginsum; - bsum += binsum; - - stackpointer = (stackpointer + 1) % div; - sir = stack[stackpointer]; - - routsum += sir[0]; - goutsum += sir[1]; - boutsum += sir[2]; - - rinsum -= sir[0]; - ginsum -= sir[1]; - binsum -= sir[2]; - - yi += w; - } - } - - bitmap.setPixels(pix, 0, w, 0, 0, w, h); - - return (bitmap); - } -} diff --git a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/GlideBlurTransform.java b/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/GlideBlurTransform.java deleted file mode 100644 index de5dd4d9e8..0000000000 --- a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/GlideBlurTransform.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.mogo.och.taxi.passenger.utils.blur; - -import android.content.Context; -import android.graphics.Bitmap; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; -import com.bumptech.glide.load.resource.bitmap.BitmapTransformation; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; - -public class GlideBlurTransform extends BitmapTransformation { - - private String key; - private int blurRadius; - - public GlideBlurTransform(String key, int blurRadius) { - this.key = key; - this.blurRadius = blurRadius; - } - - @Override - protected Bitmap transform( @NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight ) { - Bitmap bitmap = FastBlurUtil.doBlur( toTransform, 1, blurRadius ); - return bitmap; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof GlideBlurTransform) { - return ((GlideBlurTransform) obj).key.equals(key); - } - return false; - } - - @Override - public int hashCode() { - return key.hashCode(); - } - - @Override - public void updateDiskCacheKey( MessageDigest messageDigest ) { - messageDigest.update(key.getBytes(StandardCharsets.UTF_8)); - } -} \ No newline at end of file diff --git a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/StrictLineReader.java b/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/StrictLineReader.java deleted file mode 100644 index 94f756e38b..0000000000 --- a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/StrictLineReader.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (C) 2012 The Android Open Source Project - * - * 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.mogo.och.taxi.passenger.utils.blur; - -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; - -/** - * Buffers input from an {@link InputStream} for reading lines. - * - *

This class is used for buffered reading of lines. For purposes of this class, a line ends - * with "\n" or "\r\n". End of input is reported by throwing {@code EOFException}. Unterminated - * line at end of input is invalid and will be ignored, the caller may use {@code - * hasUnterminatedLine()} to detect it after catching the {@code EOFException}. - * - *

This class is intended for reading input that strictly consists of lines, such as line-based - * cache entries or cache journal. Unlike the {@link java.io.BufferedReader} which in conjunction - * with {@link java.io.InputStreamReader} provides similar functionality, this class uses different - * end-of-input reporting and a more restrictive definition of a line. - * - *

This class supports only charsets that encode '\r' and '\n' as a single byte with value 13 - * and 10, respectively, and the representation of no other character contains these values. - * We currently check in constructor that the charset is one of US-ASCII, UTF-8 and ISO-8859-1. - * The default charset is US_ASCII. - */ -class StrictLineReader implements Closeable { - private static final byte CR = (byte) '\r'; - private static final byte LF = (byte) '\n'; - - private final InputStream in; - private final Charset charset; - - /* - * Buffered data is stored in {@code buf}. As long as no exception occurs, 0 <= pos <= end - * and the data in the range [pos, end) is buffered for reading. At end of input, if there is - * an unterminated line, we set end == -1, otherwise end == pos. If the underlying - * {@code InputStream} throws an {@code IOException}, end may remain as either pos or -1. - */ - private byte[] buf; - private int pos; - private int end; - - /** - * Constructs a new {@code LineReader} with the specified charset and the default capacity. - * - * @param in the {@code InputStream} to read data from. - * @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are - * supported. - * @throws NullPointerException if {@code in} or {@code charset} is null. - * @throws IllegalArgumentException if the specified charset is not supported. - */ - public StrictLineReader(InputStream in, Charset charset) { - this(in, 8192, charset); - } - - /** - * Constructs a new {@code LineReader} with the specified capacity and charset. - * - * @param in the {@code InputStream} to read data from. - * @param capacity the capacity of the buffer. - * @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are - * supported. - * @throws NullPointerException if {@code in} or {@code charset} is null. - * @throws IllegalArgumentException if {@code capacity} is negative or zero - * or the specified charset is not supported. - */ - public StrictLineReader(InputStream in, int capacity, Charset charset) { - if (in == null || charset == null) { - throw new NullPointerException(); - } - if (capacity < 0) { - throw new IllegalArgumentException("capacity <= 0"); - } - if (!(charset.equals(Util.US_ASCII))) { - throw new IllegalArgumentException("Unsupported encoding"); - } - - this.in = in; - this.charset = charset; - buf = new byte[capacity]; - } - - /** - * Closes the reader by closing the underlying {@code InputStream} and - * marking this reader as closed. - * - * @throws IOException for errors when closing the underlying {@code InputStream}. - */ - public void close() throws IOException { - synchronized (in) { - if (buf != null) { - buf = null; - in.close(); - } - } - } - - /** - * Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"}, - * this end of line marker is not included in the result. - * - * @return the next line from the input. - * @throws IOException for underlying {@code InputStream} errors. - * @throws EOFException for the end of source stream. - */ - public String readLine() throws IOException { - synchronized (in) { - if (buf == null) { - throw new IOException("LineReader is closed"); - } - - // Read more data if we are at the end of the buffered data. - // Though it's an error to read after an exception, we will let {@code fillBuf()} - // throw again if that happens; thus we need to handle end == -1 as well as end == pos. - if (pos >= end) { - fillBuf(); - } - // Try to find LF in the buffered data and return the line if successful. - for (int i = pos; i != end; ++i) { - if (buf[i] == LF) { - int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i; - String res = new String(buf, pos, lineEnd - pos, charset.name()); - pos = i + 1; - return res; - } - } - - // Let's anticipate up to 80 characters on top of those already read. - ByteArrayOutputStream out = new ByteArrayOutputStream(end - pos + 80) { - @Override - public String toString() { - int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count; - try { - return new String(buf, 0, length, charset.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); // Since we control the charset this will never happen. - } - } - }; - - while (true) { - out.write(buf, pos, end - pos); - // Mark unterminated line in case fillBuf throws EOFException or IOException. - end = -1; - fillBuf(); - // Try to find LF in the buffered data and return the line if successful. - for (int i = pos; i != end; ++i) { - if (buf[i] == LF) { - if (i != pos) { - out.write(buf, pos, i - pos); - } - pos = i + 1; - return out.toString(); - } - } - } - } - } - - /** - * Reads new input data into the buffer. Call only with pos == end or end == -1, - * depending on the desired outcome if the function throws. - */ - private void fillBuf() throws IOException { - int result = in.read(buf, 0, buf.length); - if (result == -1) { - throw new EOFException(); - } - pos = 0; - end = result; - } -} - diff --git a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/Util.java b/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/Util.java deleted file mode 100644 index 05f0c2e994..0000000000 --- a/OCH/taxi/passenger/src/main/java/com/mogo/och/taxi/passenger/utils/blur/Util.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * 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.mogo.och.taxi.passenger.utils.blur; - -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.io.StringWriter; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; - -/** Junk drawer of utility methods. */ -final class Util { - static final Charset US_ASCII = StandardCharsets.US_ASCII; - static final Charset UTF_8 = StandardCharsets.UTF_8; - - private Util() { - } - - static String readFully(Reader reader) throws IOException { - try { - StringWriter writer = new StringWriter(); - char[] buffer = new char[1024]; - int count; - while ((count = reader.read(buffer)) != -1) { - writer.write(buffer, 0, count); - } - return writer.toString(); - } finally { - reader.close(); - } - } - - /** - * Deletes the contents of {@code dir}. Throws an IOException if any file - * could not be deleted, or if {@code dir} is not a readable directory. - */ - static void deleteContents(File dir) throws IOException { - File[] files = dir.listFiles(); - if (files == null) { - throw new IOException("not a readable directory: " + dir); - } - for (File file : files) { - if (file.isDirectory()) { - deleteContents(file); - } - if (!file.delete()) { - throw new IOException("failed to delete file: " + file); - } - } - } - - static void closeQuietly(/*Auto*/Closeable closeable) { - if (closeable != null) { - try { - closeable.close(); - } catch (RuntimeException rethrown) { - throw rethrown; - } catch (Exception ignored) { - } - } - } -} \ No newline at end of file diff --git a/OCH/taxi/unmanned-passenger/src/main/java/com/mogo/och/taxi/passenger/ui/arrived/RightRearCamView.kt b/OCH/taxi/unmanned-passenger/src/main/java/com/mogo/och/taxi/passenger/ui/arrived/RightRearCamView.kt index 336357d774..655a132350 100644 --- a/OCH/taxi/unmanned-passenger/src/main/java/com/mogo/och/taxi/passenger/ui/arrived/RightRearCamView.kt +++ b/OCH/taxi/unmanned-passenger/src/main/java/com/mogo/och/taxi/passenger/ui/arrived/RightRearCamView.kt @@ -5,7 +5,6 @@ import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable import android.util.AttributeSet -import android.util.Log import android.view.LayoutInflater import androidx.constraintlayout.widget.ConstraintLayout import com.mogo.eagle.core.function.api.autopilot.IMoGoBackCameraVideoListener @@ -128,7 +127,7 @@ class RightRearCamView : ConstraintLayout , IMoGoBackCameraVideoListener, private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int { val width = options.outWidth val height = options.outHeight - Log.i(TAG, "calculateInSampleSize: out width and height is $width height $height") + d(SceneConstant.M_TAXI_P + TAG, "calculateInSampleSize: out width and height is $width height $height") var inSampleWidth = 1 if (height > reqHeight || width > reqWidth) { val halfHeight = height / 2 diff --git a/app/script/flavorfilter/flavors.json b/app/script/flavorfilter/flavors.json index 15da63986b..698df829eb 100644 --- a/app/script/flavorfilter/flavors.json +++ b/app/script/flavorfilter/flavors.json @@ -15,12 +15,10 @@ }, "taxi" :{ "driver": ["ochDFHQ"], - "driverPassenger": ["ochDFHQ"], "passenger": ["ochDFHQ"] }, "bus" :{ "driver": ["ochJL"], - "driverPassenger": ["ochJL"], "passenger": ["ochJL"] }, "charter" :{ @@ -54,7 +52,6 @@ "saas": { "taxiunmanned" :{ "driver": ["ochDFHQ"], - "driverpassenger": ["ochDFHQ"], "passenger": ["ochDFHQ"] }, "shuttle" :{ @@ -63,7 +60,6 @@ }, "bus" :{ "driver": ["ochJL"], - "driverPassenger": ["ochJL"], "passenger": ["ochJL"] }, "charter" :{ diff --git a/app/script/productFlavors/bus.gradle b/app/script/productFlavors/bus.gradle index 1aeb2c155d..0597162542 100644 --- a/app/script/productFlavors/bus.gradle +++ b/app/script/productFlavors/bus.gradle @@ -8,9 +8,9 @@ project.android.productFlavors { // 标识 CHANNEL_VALUE_HEAD: "Bus", // 在启动的时候把Task给清空 - ACTIVITY_ROOT : true, +// ACTIVITY_ROOT : true, // Activity的朝向 - SCREEN_ORIENTATION:"landscape", +// SCREEN_ORIENTATION:"landscape", ] // ①标识 diff --git a/app/script/productFlavors/charter.gradle b/app/script/productFlavors/charter.gradle index b657f22013..1177dbf48f 100644 --- a/app/script/productFlavors/charter.gradle +++ b/app/script/productFlavors/charter.gradle @@ -8,9 +8,9 @@ project.android.productFlavors { manifestPlaceholders = [ CHANNEL_VALUE_HEAD: "Charter", // 在启动的时候把Task给清空 - ACTIVITY_ROOT : true, +// ACTIVITY_ROOT : true, // Activity的朝向 - SCREEN_ORIENTATION:"landscape", +// SCREEN_ORIENTATION:"landscape", ] // ①标识 buildConfigField 'String', 'APP_IDENTITY_MODE_HEAD', "\"Charter\"" diff --git a/app/script/productFlavors/noop.gradle b/app/script/productFlavors/noop.gradle index 4c0e0dd5b6..5ffbeab9f6 100644 --- a/app/script/productFlavors/noop.gradle +++ b/app/script/productFlavors/noop.gradle @@ -7,9 +7,9 @@ project.android.productFlavors { // 标识 CHANNEL_VALUE_HEAD: "Noop", // 在启动的时候把Task给清空 - ACTIVITY_ROOT : true, +// ACTIVITY_ROOT : true, // Activity的朝向 - SCREEN_ORIENTATION:"landscape", +// SCREEN_ORIENTATION:"landscape", ] // ①标识 diff --git a/app/script/productFlavors/shuttle.gradle b/app/script/productFlavors/shuttle.gradle index 0ea25aec59..dbe16ce151 100644 --- a/app/script/productFlavors/shuttle.gradle +++ b/app/script/productFlavors/shuttle.gradle @@ -9,7 +9,7 @@ project.android.productFlavors { // 标识 CHANNEL_VALUE_HEAD: "Shuttle", // 在启动的时候把Task给清空 - ACTIVITY_ROOT : true, +// ACTIVITY_ROOT : true, ] // ①标识 diff --git a/app/script/productFlavors/sweeperCloud.gradle b/app/script/productFlavors/sweeperCloud.gradle index 5c9bbc338c..6ed013d84c 100644 --- a/app/script/productFlavors/sweeperCloud.gradle +++ b/app/script/productFlavors/sweeperCloud.gradle @@ -7,9 +7,9 @@ project.android.productFlavors { // 标识 CHANNEL_VALUE_HEAD: "Sweeper", // 在启动的时候把Task给清空 - ACTIVITY_ROOT : true, +// ACTIVITY_ROOT : true, // Activity的朝向 - SCREEN_ORIENTATION:"landscape", +// SCREEN_ORIENTATION:"landscape", ] // ①标识 diff --git a/app/script/productFlavors/sweeperOperate.gradle b/app/script/productFlavors/sweeperOperate.gradle index 9e14e1684e..0b28338337 100644 --- a/app/script/productFlavors/sweeperOperate.gradle +++ b/app/script/productFlavors/sweeperOperate.gradle @@ -7,9 +7,9 @@ project.android.productFlavors { // 标识 CHANNEL_VALUE_HEAD: "Sweeper", // 在启动的时候把Task给清空 - ACTIVITY_ROOT : true, +// ACTIVITY_ROOT : true, // Activity的朝向 - SCREEN_ORIENTATION:"landscape", +// SCREEN_ORIENTATION:"landscape", ] // ①标识 diff --git a/app/script/productFlavors/taxi.gradle b/app/script/productFlavors/taxi.gradle index 8a3ff987e2..6564946ad4 100644 --- a/app/script/productFlavors/taxi.gradle +++ b/app/script/productFlavors/taxi.gradle @@ -6,7 +6,7 @@ project.android.productFlavors { manifestPlaceholders = [ CHANNEL_VALUE_HEAD: "Taxi", // Activity的朝向 - SCREEN_ORIENTATION:"landscape", +// SCREEN_ORIENTATION:"landscape", ] // ①标识 buildConfigField 'String', 'APP_IDENTITY_MODE_HEAD', "\"Taxi\"" diff --git a/app/script/productFlavors/taxiunmanned.gradle b/app/script/productFlavors/taxiunmanned.gradle index da4280e89c..84c7697b6a 100644 --- a/app/script/productFlavors/taxiunmanned.gradle +++ b/app/script/productFlavors/taxiunmanned.gradle @@ -6,7 +6,7 @@ project.android.productFlavors { manifestPlaceholders = [ CHANNEL_VALUE_HEAD: "Taxi", // Activity的朝向 - SCREEN_ORIENTATION:"landscape", +// SCREEN_ORIENTATION:"landscape", ] // ①标识 buildConfigField 'String', 'APP_IDENTITY_MODE_HEAD', "\"Taxi\"" diff --git a/app_mogo_magic_ring/src/main/java/com/zhidao/adas/magic/ui/MainActivity.java b/app_mogo_magic_ring/src/main/java/com/zhidao/adas/magic/ui/MainActivity.java index 74865240ba..d5d62fca87 100644 --- a/app_mogo_magic_ring/src/main/java/com/zhidao/adas/magic/ui/MainActivity.java +++ b/app_mogo_magic_ring/src/main/java/com/zhidao/adas/magic/ui/MainActivity.java @@ -684,7 +684,6 @@ public class MainActivity extends BaseActivity implements OnAdasListener, OnAdas @Override public void onConnectionIPCStatus(int ipcConnectionStatus, String reason) { -// Log.i(TAG, "连接状态=" + (reason == null ? "主动断开连接" : reason)); String time = sdf.format(new Date()); connectStatusList.add(0, new IPCConnectState(reason == null ? "主动断开连接" : reason, getStatusColor(ipcConnectionStatus))); if (connectStatusList.size() > 100) { diff --git a/build.gradle b/build.gradle index 190f5f0714..61b458a85c 100644 --- a/build.gradle +++ b/build.gradle @@ -15,13 +15,9 @@ buildscript { maven { url 'https://maven.aliyun.com/repository/google' } maven { url 'https://maven.aliyun.com/repository/gradle-plugin' } maven { url 'https://maven.aliyun.com/repository/jcenter' } - - maven { - url "https://artifact.bytedance.com/repository/Volcengine/" - } - maven { - url "https://artifact.bytedance.com/repository/byteX/" - } + maven { url "https://plugins.gradle.org/m2/" } + maven { url "https://artifact.bytedance.com/repository/Volcengine/" } + maven { url "https://artifact.bytedance.com/repository/byteX/" } gradlePluginPortal() // mavenCentral() google() @@ -41,6 +37,7 @@ buildscript { classpath "io.github.knight-zxw:lancet-plugin:${lancetx_plugin_version}" classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.15.0" classpath 'com.mogo.cloud:matrix:1.0.0' + classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.4.0.2513' // classpath 'com.bytedance.btrace:rhea-gradle-plugin:2.0.0' } // 遇无法更新依赖情况(针对Snapshot无法刷新)然后sync project即可,刷新完成注释该代码 @@ -62,6 +59,7 @@ allprojects { maven { url 'https://maven.aliyun.com/repository/google' } maven { url 'https://maven.aliyun.com/repository/gradle-plugin' } maven { url 'https://maven.aliyun.com/repository/jcenter' } + maven { url 'https://plugins.gradle.org/m2/' } // mavenCentral() maven { @@ -73,7 +71,7 @@ allprojects { google() } - if (isCodeInspectEnable ) { + if (isCodeInspectEnable) { def basePath = new File(codequality, 'code_inspect_increment.gradle').path apply from: "$basePath" def pmdPath = new File(codequality, 'pmd.gradle').path @@ -85,6 +83,9 @@ allprojects { } } +apply plugin: 'jacoco' +apply from: rootProject.file('codequality/sonar.gradle') + task clean(type: Delete) { delete rootProject.buildDir } diff --git a/codequality/sonar.gradle b/codequality/sonar.gradle new file mode 100644 index 0000000000..94030dde8a --- /dev/null +++ b/codequality/sonar.gradle @@ -0,0 +1,19 @@ +apply plugin: 'org.sonarqube' + +sonarqube { + properties { + property "sonar.log.level", "TRACE" + property "sonar.sourceEncoding", "UTF-8" + property "sonar.projectKey", "MoGoEagleEyeTest" + property "sonar.sources", "src/main/java" + property "sonar.binaries", "build/intermediates/classes" + property "sonar.qualitygate.wait", true + property "sonar.android.lint.report", false + property "sonar.scm.exclusions.disabled", false + property "sonar.scm.exclusions.file", "**/.gitignore" + property "sonar.exclusions", "**/AndroidManifest.xml, **/src/test/**, com/mogo/eagle/core/utilcode, **/*.jar, **/*.aar, **/*.war, **/*.ear, **/*.rar, **/*.tgz, **/*.zip, **/src/test/java/**/*.java, **/src/test/java/**/*.kt, **/test/**/*, **/*Test.java, **/*Tests.java, **/*Test.kt, **/*.xml,*.xml, **/target/**, **/src/main/java/proto/**, **/build/**, build, build/**, **/db/dao/*.java, **/build/intermediates/**/*" +// property "sonar.java.coveragePlugin", "jacoco" +// property("sonar.coverage.jacoco.xmlReportPaths", "../../build/reports/jacocoTestReport.xml,../build/reports/jacocoTestReport.xml") + } +} + diff --git a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/dispatch/DispatchAutoPilotManager.kt b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/dispatch/DispatchAutoPilotManager.kt index 38f79472f2..997fdb61a0 100644 --- a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/dispatch/DispatchAutoPilotManager.kt +++ b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/dispatch/DispatchAutoPilotManager.kt @@ -2,6 +2,7 @@ package com.mogo.eagle.function.biz.dispatch import android.content.Context import android.os.Handler +import android.os.Looper import android.os.Message import com.mogo.aicloud.services.socket.IMogoOnMessageListener import com.mogo.aicloud.services.socket.MogoAiCloudSocketManager @@ -9,6 +10,7 @@ import com.mogo.commons.voice.AIAssist import com.mogo.eagle.core.data.autopilot.AutopilotControlParameters import com.mogo.eagle.core.data.autopilot.AutopilotRouteInfo import com.mogo.eagle.core.data.biz.dispatch.DispatchAdasAutoPilotLocReceiverBean +import com.mogo.eagle.core.data.deva.chain.ChainConstant import com.mogo.eagle.core.data.map.MogoLatLng import com.mogo.eagle.core.function.api.autopilot.IMoGoAutopilotStatusListener import com.mogo.eagle.core.function.api.autopilot.IMoGoPlanningRottingListener @@ -31,11 +33,12 @@ import com.mogo.eagle.function.biz.dispatch.network.DispatchServiceModel.Compani import com.mogo.eagle.function.biz.dispatch.network.DispatchServiceModel.Companion.DISPATCH_STOP_MANUAL_CANCEL import com.mogo.eagle.function.biz.dispatch.network.DispatchServiceModel.Companion.DISPATCH_STOP_TIMER_CANCEL import com.mogo.eagle.function.biz.dispatch.network.DispatchServiceModel.Companion.dispatchServiceModel +import com.mogo.eagle.function.biz.v2x.V2XBizTrace import com.zhjt.mogo.adas.data.bean.MogoReport +import com.zhjt.service.chain.ChainLog import mogo.telematics.pad.MessagePad import mogo_msg.MogoReportMsg -//todo emArrow 添加biz链路日志 //负责监听自动驾驶状态并进行状态上报,自动驾驶路线上报,接收调度指令展示指令弹窗 class DispatchAutoPilotManager private constructor() : IMogoOnMessageListener, @@ -61,7 +64,7 @@ class DispatchAutoPilotManager private constructor() : private var isDispatch = false private var isArriveEnd = false - private val handler: Handler = object : Handler() { + private val handler: Handler = object : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { super.handleMessage(msg) if (msg.what == MSG_TYPE_SHOW_DIALOG) { @@ -109,6 +112,12 @@ class DispatchAutoPilotManager private constructor() : return DispatchAdasAutoPilotLocReceiverBean::class.java } + @ChainLog( + linkChainLog = ChainConstant.CHAIN_TYPE_V2X, + linkCode = ChainConstant.CHAIN_SOURCE_CLOUD, + nodeAliasCode = ChainConstant.CHAIN_CODE_DISPATCH_RECEIVE, + paramIndexes = [0] + ) override fun onMsgReceived(adasAutoPilotLocReceiverBean: DispatchAdasAutoPilotLocReceiverBean?) { CallerLogger.i("$M_BIZ$TAG","onMsgReceived 收到云调度长链接, adasAutoPilotLocReceiver:${adasAutoPilotLocReceiverBean?:""}") if (adasAutoPilotLocReceiverBean != null && adasAutoPilotLocReceiverBean.startLat != 0.0 && adasAutoPilotLocReceiverBean.startLon != 0.0) { @@ -130,6 +139,12 @@ class DispatchAutoPilotManager private constructor() : } } + @ChainLog( + linkChainLog = ChainConstant.CHAIN_TYPE_V2X, + linkCode = ChainConstant.CHAIN_SOURCE_CLOUD, + nodeAliasCode = ChainConstant.CHAIN_CODE_DISPATCH_START, + paramIndexes = [-1] + ) private fun startAutoPilot() { val currentAutopilot = AutopilotControlParameters() // currentAutopilot.isSpeakVoice = false @@ -146,34 +161,42 @@ class DispatchAutoPilotManager private constructor() : } } if(it.trajUrl == null){ + V2XBizTrace.onAck(M_BIZ + TAG, "trajUrl-null") ToastUtils.showShort("trajUrl数据为空") return } if(it.trajMd5 == null){ + V2XBizTrace.onAck(M_BIZ + TAG, "trajMd5-null") ToastUtils.showShort("trajMd5数据为空") return } if(it.stopUrl == null){ + V2XBizTrace.onAck(M_BIZ + TAG, "stopUrl-null") ToastUtils.showShort("stopUrl数据为空") return } if(it.stopMd5 == null){ + V2XBizTrace.onAck(M_BIZ + TAG, "stopMd5-null") ToastUtils.showShort("stopMd5数据为空") return } if(it.vehicleModel == null){ + V2XBizTrace.onAck(M_BIZ + TAG, "vehicleModel-null") ToastUtils.showShort("vehicleModel数据为空") return } if(it.lineName == null){ + V2XBizTrace.onAck(M_BIZ + TAG, "lineName-null") ToastUtils.showShort("lineName数据为空") return } if(it.startLocAddress == null){ + V2XBizTrace.onAck(M_BIZ + TAG, "startLocAddress-null") ToastUtils.showShort("startLocAddress数据为空") return } if(it.endLocAddress == null){ + V2XBizTrace.onAck(M_BIZ + TAG, "endLocAddress-null") ToastUtils.showShort("endLocAddress数据为空") return } @@ -191,7 +214,7 @@ class DispatchAutoPilotManager private constructor() : currentAutopilot.endLatLon = AutopilotControlParameters.AutoPilotLonLat(it.endLat, it.endLon) currentAutopilot.vehicleType = 10 - CallerLogger.d(M_BIZ + TAG, "开启自动驾驶====$currentAutopilot") + V2XBizTrace.onAck(M_BIZ + TAG, "开启自动驾驶====$currentAutopilot") CallerAutoPilotControlManager.startAutoPilot(currentAutopilot) } } @@ -213,6 +236,7 @@ class DispatchAutoPilotManager private constructor() : * 停止调度确认 */ fun stopAffirm(){ + V2XBizTrace.onAck(M_BIZ + TAG,"stopAffirm") CallerHmiManager.dismissDispatchDialog() receiverBean?.taskId?.let{ dispatchServiceModel.dispatchResultUpload(DISPATCH_STOP_AFFIRM, it, @@ -230,6 +254,7 @@ class DispatchAutoPilotManager private constructor() : } fun cancel(manualTrigger: Boolean) { + V2XBizTrace.onAck(M_BIZ + TAG,"cancel") CallerHmiManager.dismissDispatchDialog() receiverBean?.taskId?.let { dispatchServiceModel.dispatchResultUpload( @@ -241,6 +266,7 @@ class DispatchAutoPilotManager private constructor() : * 停止调度取消 */ fun stopCancel(manualTrigger: Boolean){ + V2XBizTrace.onAck(M_BIZ + TAG,"stopCancel:$manualTrigger") CallerHmiManager.dismissDispatchDialog() receiverBean?.taskId?.let{ dispatchServiceModel.dispatchResultUpload( @@ -263,9 +289,6 @@ class DispatchAutoPilotManager private constructor() : if (isArriveEnd) { return } - //todo 确认是否要根据停靠时自动驾驶状态,再次开启自动驾驶 - // 确保处于调度中并且返回的自动驾驶状态为1才开启自动驾驶 - // 上述等待鄂州项目复盘后,产品输出完成方案后再进操作!!! if (isDispatch) { startAutoPilot() } @@ -324,6 +347,8 @@ class DispatchAutoPilotManager private constructor() : //语音提示到站 AIAssist.getInstance(mContext).speakTTSVoice("云调度完成,车辆已到达${it.endLocAddress}") } + }else{ + V2XBizTrace.onAck(M_BIZ + TAG, mapOf("ArriveAtStation" to arrivalNotification, "distanceFromSelf" to distanceFromSelf)) } } diff --git a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/notice/network/NoticeNetWorkManager.java b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/notice/network/NoticeNetWorkManager.java index 6b92808023..946f602fc8 100644 --- a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/notice/network/NoticeNetWorkManager.java +++ b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/notice/network/NoticeNetWorkManager.java @@ -30,7 +30,6 @@ import okhttp3.RequestBody; * @since: 10/28/21 */ public class NoticeNetWorkManager { - private static volatile NoticeNetWorkManager requestNoticeManager; private final INoticeApiService mNoticeApiService; private NoticeNetWorkManager() { @@ -39,14 +38,11 @@ public class NoticeNetWorkManager { } public static NoticeNetWorkManager getInstance() { - if (requestNoticeManager == null) { - synchronized (NoticeNetWorkManager.class) { - if (requestNoticeManager == null) { - requestNoticeManager = new NoticeNetWorkManager(); - } - } - } - return requestNoticeManager; + return Holder.requestNoticeManager; + } + + private static final class Holder{ + private static final NoticeNetWorkManager requestNoticeManager = new NoticeNetWorkManager(); } /** @@ -88,7 +84,7 @@ public class NoticeNetWorkManager { * 反馈交警是否接受事故任务 * * @param infoId 事故id - * @param sn + * @param sn sn * @param status 是否接受 0否 1是 */ public void sendAccidentAcceptStatus(String infoId, String sn, int status) { diff --git a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/obu/V2xObuEventManager.kt b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/obu/V2xObuEventManager.kt index 8dd062988f..9b708319ed 100644 --- a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/obu/V2xObuEventManager.kt +++ b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/obu/V2xObuEventManager.kt @@ -11,6 +11,7 @@ import com.mogo.eagle.core.function.call.msgbox.CallerMsgBoxManager import com.mogo.eagle.core.function.call.obu.CallerObuSaveMessageListenerManager import com.mogo.eagle.core.utilcode.mogo.logger.CallerLogger import com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant +import com.mogo.eagle.function.biz.v2x.V2XBizTrace import com.mogo.eagle.function.biz.v2x.v2n.utils.V2XEventAnalyticsManager /** @@ -53,7 +54,7 @@ object V2xObuEventManager : IMoGoObuSaveMessageListener { } } obuDataMap[type] = System.currentTimeMillis() - CallerLogger.d("${SceneConstant.M_OBU}${TAG}", "onMoGoObuSaveMessage type = $type ---content = $content ---tts = $tts ") + V2XBizTrace.onAck("${SceneConstant.M_OBU}${TAG}", mapOf("type" to type,"content" to content,"tts" to tts)) CallerMsgBoxManager.saveMsgBox( MsgBoxBean( MsgBoxType.V2X, diff --git a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/redlightwarning/RedLightWarningManager.kt b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/redlightwarning/RedLightWarningManager.kt index 9beb4fd4fb..f1d97cce21 100644 --- a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/redlightwarning/RedLightWarningManager.kt +++ b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/redlightwarning/RedLightWarningManager.kt @@ -1,6 +1,5 @@ package com.mogo.eagle.function.biz.v2x.redlightwarning -import android.util.Log import com.mogo.eagle.core.data.biz.trafficlight.* import com.mogo.eagle.core.data.deva.bizconfig.FuncBizConfig.Companion.BIZ_IVP import com.mogo.eagle.core.data.deva.bizconfig.FuncBizConfig.Companion.BIZ_IVP_GREEN @@ -235,9 +234,6 @@ class RedLightWarningManager : IMoGoTrafficLightListener, IMoGoVipSetListener, EventTypeEnumNew.getWarningTts(EventTypeEnumNew.TYPE_USECASE_ID_IVP_GREEN.poiType), speed ) - if (content.isEmpty() || tts.isEmpty()) { - Log.d("MsgBox-RedLightWarManaG", "alertContent或ttsContent为空!") - } CallerMsgBoxManager.saveMsgBox( MsgBoxBean( MsgBoxType.V2X, diff --git a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/V2XEventManager.kt b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/V2XEventManager.kt index 153d7b0762..0732986068 100644 --- a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/V2XEventManager.kt +++ b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/V2XEventManager.kt @@ -7,6 +7,7 @@ import androidx.annotation.* import androidx.localbroadcastmanager.content.* import com.mogo.eagle.core.data.config.* import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_CODE_V2X_MSG +import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_SOURCE_ADAS import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_SOURCE_CLOUD import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_V2X import com.mogo.eagle.core.data.enums.* @@ -182,7 +183,7 @@ object V2XEventManager : IMoGoChassisLocationGCJ02Listener, IV2XCallback, @RequiresApi(Build.VERSION_CODES.N) @ChainLog( linkChainLog = CHAIN_TYPE_V2X, - linkCode = CHAIN_SOURCE_CLOUD, + linkCode = CHAIN_SOURCE_ADAS, nodeAliasCode = CHAIN_CODE_V2X_MSG, paramIndexes = [0] ) @@ -301,6 +302,7 @@ object V2XEventManager : IMoGoChassisLocationGCJ02Listener, IV2XCallback, val msgBoxBean = MsgBoxBean(MsgBoxType.V2X, V2XMsg("", "查询到当前全程共${count}个事件", "",CommunicationType.V2N.name)) msgBoxBean.sourceType = DataSourceType.SUMMARY + V2XBizTrace.onAck("$M_V2X$TAG", mapOf("v2xEventsSummary" to msgBoxBean)) CallerMsgBoxManager.saveMsgBox(msgBoxBean) //消息埋点 V2XEventAnalyticsManager.triggerV2XEvent("summary","查询到当前全程共${count}个事件", diff --git a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/V2XPoiLoader.kt b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/V2XPoiLoader.kt index f1b96ff6f1..1835084bda 100644 --- a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/V2XPoiLoader.kt +++ b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/V2XPoiLoader.kt @@ -12,7 +12,9 @@ import com.mogo.eagle.core.data.v2x.V2XEvent import com.mogo.eagle.core.data.v2x.V2XMarkerResponse import com.mogo.eagle.core.function.call.autopilot.CallerAutoPilotStatusListenerManager import com.mogo.eagle.core.function.call.msgbox.CallerMsgBoxManager +import com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant import com.mogo.eagle.core.utilcode.util.UiThreadHandler +import com.mogo.eagle.function.biz.v2x.V2XBizTrace import com.mogo.eagle.function.biz.v2x.v2n.network.V2XRefreshModel import com.mogo.eagle.function.biz.v2x.v2n.network.callback.IV2XCallback import com.mogo.eagle.function.biz.v2x.v2n.network.callback.IV2XRefreshCallback @@ -160,6 +162,7 @@ class V2XPoiLoader private constructor() { val msgBoxBean = MsgBoxBean(MsgBoxType.V2X, V2XMsg("", "查询到当前全程共${size}个事件", "",CommunicationType.V2N.name)) msgBoxBean.sourceType = DataSourceType.SUMMARY + V2XBizTrace.onAck("${SceneConstant.M_V2X}$TAG", mapOf("v2xEventsSummary" to msgBoxBean)) CallerMsgBoxManager.saveMsgBox(msgBoxBean) //消息埋点 V2XEventAnalyticsManager.triggerV2XEvent("summary","查询到当前全程共${size}个事件", diff --git a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/pnc/V2NIdentifyDrawer.kt b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/pnc/V2NIdentifyDrawer.kt index b2d02ed02c..82d0486c8d 100644 --- a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/pnc/V2NIdentifyDrawer.kt +++ b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/pnc/V2NIdentifyDrawer.kt @@ -17,7 +17,6 @@ import com.mogo.eagle.core.function.call.hmi.* import com.mogo.eagle.core.function.call.map.* import com.mogo.eagle.core.function.call.msgbox.CallerMsgBoxManager.saveMsgBox import com.mogo.eagle.core.utilcode.mogo.* -import com.mogo.eagle.core.utilcode.mogo.logger.* import com.mogo.eagle.core.utilcode.util.* import com.mogo.eagle.function.biz.v2x.V2XBizTrace import com.mogo.eagle.function.biz.v2x.v2n.scenario.scene.airoad.* @@ -33,7 +32,6 @@ import mogo.v2x.MogoV2X.RSI_PB */ internal object V2NIdentifyDrawer { - private const val TAG = "V2NIdentifyDataSubscriber" private const val MSG_WHAT_DRAW_SHIGONE = 0x1010 // 道路施工 @@ -44,6 +42,7 @@ internal object V2NIdentifyDrawer { if (msg.what == MSG_WHAT_DRAW_SHIGONE || msg.what == MSG_WHAT_DRAW_SHIGU) { val events = msg.obj as? List<*> if (events == null || events.isEmpty()) { + V2XBizTrace.onAck(TAG, mapOf("shiGong-shiGu" to "")) return@Callback true } val car = CallerChassisLocationWGS84ListenerManager.getChassisLocationWGS84() @@ -51,6 +50,7 @@ internal object V2NIdentifyDrawer { DrivingDirectionUtils.getDegreeOfCar2Poi(car.longitude, car.latitude, itx.longitude, itx.latitude, car.heading.toInt()) < 90 } if (filtered.isEmpty()) { + V2XBizTrace.onAck(TAG, mapOf("shiGong-shiGu-filter" to "")) return@Callback true } filtered.forEach { itx -> @@ -78,7 +78,7 @@ internal object V2NIdentifyDrawer { val distance = CoordinateUtils.calculateLineDistance(itx.longitude, itx.latitude, car.longitude, car.latitude) val alertContent = getAlertContent(poiType, distance.toDouble()) val ttsContent = getTtsContent(poiType, distance.toDouble()) - V2XBizTrace.onAck("V2NIdentifyDrawer","绘制poi事件:$poiType") + V2XBizTrace.onAck(TAG,"绘制poi事件:$poiType") saveMsgBox(MsgBoxBean(V2X, V2XMsg(poiType, alertContent, ttsContent,CommunicationType.V2N.name))) CallerHmiManager.warningV2X(poiType, alertContent, ttsContent, object : IMoGoWarningStatusListener { override fun onShow() { @@ -100,6 +100,7 @@ internal object V2NIdentifyDrawer { } else if (msg.what == MSG_WHAT_DRAW_YONGDU) { val events = msg.obj as? List<*> if (events == null || events.isEmpty()) { + V2XBizTrace.onAck(TAG, mapOf("yongDu" to "")) return@Callback true } val car = CallerChassisLocationWGS84ListenerManager.getChassisLocationWGS84() @@ -109,6 +110,7 @@ internal object V2NIdentifyDrawer { DrivingDirectionUtils.getDegreeOfCar2Poi(car.longitude, car.latitude, eventLon, eventLat, car.heading.toInt()) < 90 } if (filtered.isEmpty()) { + V2XBizTrace.onAck(TAG, mapOf("yongDu-filter" to "")) return@Callback true } filtered.forEach { itx -> @@ -137,6 +139,7 @@ internal object V2NIdentifyDrawer { val distance = CoordinateUtils.calculateLineDistance(lon, lat, car.longitude, car.latitude) val alertContent = getAlertContent(poiType, distance.toDouble()) val ttsContent = getTtsContent(poiType, distance.toDouble()) + V2XBizTrace.onAck(TAG,"绘制poi事件:$poiType") saveMsgBox(MsgBoxBean(V2X, V2XMsg(poiType, alertContent, ttsContent,CommunicationType.V2N.name))) CallerHmiManager.warningV2X(poiType, alertContent, ttsContent, object : IMoGoWarningStatusListener { override fun onShow() { @@ -221,7 +224,6 @@ internal object V2NIdentifyDrawer { override fun onAutopilotV2nCongestionEvent(header: Header, rsi: RSI_PB) { super.onAutopilotV2nCongestionEvent(header, rsi) - Logger.d(TAG, "--- onAutopilotV2nCongestionEvent -- : rsi: ${ GsonUtils.toJson(rsi) }") try { V2XBizTrace.onAck("onAutopilotV2nCongestionEvent", rsi) } catch (t: Throwable) { diff --git a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/scenario/scene/airoad/AiRoadMarker.kt b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/scenario/scene/airoad/AiRoadMarker.kt index 68f996cfd0..82a986e606 100644 --- a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/scenario/scene/airoad/AiRoadMarker.kt +++ b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/scenario/scene/airoad/AiRoadMarker.kt @@ -101,7 +101,7 @@ class AiRoadMarker { 300f, call = { result -> //施工中心点后方的自车行驶方向上300米距离 result?.let { - V2XBizTrace.onAck("$TAG --- marker --- 3 --- l1:", it) + V2XBizTrace.onAck("$TAG -marker-3-l1:", it) l1 = result } countDown.incrementAndGet() @@ -113,7 +113,7 @@ class AiRoadMarker { location.heading.toFloat(), -300f, call = { result -> result?.let { - V2XBizTrace.onAck("$TAG --- marker --- 3 --- l2:", it) + V2XBizTrace.onAck("$TAG -marker-3-l2:", it) l2 = result } countDown.incrementAndGet() @@ -136,14 +136,14 @@ class AiRoadMarker { return@post } if (l1 == null || l2 == null) { - V2XBizTrace.onAck("$TAG --- marker --- 3 --- line null return ----", "") + V2XBizTrace.onAck("$TAG -marker-3-line null return ----", "") return@post } if (l1.points.isEmpty() || l2.points.isEmpty()) { - V2XBizTrace.onAck("$TAG --- marker --- 3 --- line points null return ----", "") + V2XBizTrace.onAck("$TAG -marker-3-line points null return ----", "") return@post } - V2XBizTrace.onAck("$TAG --- marker --- 4 --- l2:", l2) + V2XBizTrace.onAck("$TAG -marker-4-l2:", l2) val points = LinkedList() if (l2.points.isNotEmpty()) { points.addAll(l2.points.reversed().map { @@ -152,7 +152,7 @@ class AiRoadMarker { } val centerX = marker.poi_lon val centerY = marker.poi_lat - V2XBizTrace.onAck("$TAG --- marker --- 5 --- marker:", marker) + V2XBizTrace.onAck("$TAG -marker-5-marker:", marker) val farthestPoint = marker.polygon?.let { var find: Pair = Pair(centerX, centerY) var min = Long.MAX_VALUE @@ -172,7 +172,7 @@ class AiRoadMarker { MogoLatLng(find.second, find.first) } ?: MogoLatLng(centerY, centerX) marker.farthestPoint = Pair(farthestPoint.lon, farthestPoint.lat) - V2XBizTrace.onAck("$TAG --- marker --- 6 --- marker:", marker) + V2XBizTrace.onAck("$TAG -marker-6-marker:", marker) if (l1.points.isNotEmpty()) { for (l in l1.points) { if (DrivingDirectionUtils.getDegreeOfCar2Poi2( @@ -204,7 +204,7 @@ class AiRoadMarker { builder.points(points) builder.colors(colors) builder.setVisible(true) - V2XBizTrace.onAck("$TAG --- marker --- 7 --- points:", "${points.size}") + V2XBizTrace.onAck("$TAG -marker-7-points:", "${points.size}") val line = overlayManager?.showOrUpdateLine(builder.build()) if (line != null) { this.line.set(line) @@ -220,9 +220,9 @@ class AiRoadMarker { private fun removeLine() { val old = line.get() - V2XBizTrace.onAck("$TAG --- removeRedLine --- 1", "") + V2XBizTrace.onAck("$TAG -removeRedLine-1", "") if (old != null) { - V2XBizTrace.onAck("$TAG --- removeRedLine --- 2", "") + V2XBizTrace.onAck("$TAG -removeRedLine-2", "") line.set(null) old.delegate?.remove() } @@ -230,7 +230,7 @@ class AiRoadMarker { private fun unMarker(marker: Marker) { v2nDrawHandler.post { - V2XBizTrace.onAck("$TAG --- unMarker ---", "") + V2XBizTrace.onAck("$TAG -unMarker-", "") this.marker.set(null) removeLine() roadMarker.removeMarkers() @@ -240,7 +240,7 @@ class AiRoadMarker { } fun receive() { - V2XBizTrace.onAck("$TAG --- receive --- 1 ---", "") + V2XBizTrace.onAck("$TAG -receive-1-", "") val poi = this.marker.get() val car = CallerChassisLocationWGS84ListenerManager.getChassisLocationWGS84() if (poi != null) { @@ -251,7 +251,7 @@ class AiRoadMarker { poi.poi_lat ) V2XBizTrace.onAck( - "$TAG --- receive --- 2 ---", + "$TAG -receive-2-", "car:[${car.longitude}, ${car.latitude}] -> poi:[${poi.poi_lon}, ${poi.poi_lat}] --> distance:$distance" ) if (distance < 500) { diff --git a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/scenario/scene/warning/V2XFrontWarningScenario.java b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/scenario/scene/warning/V2XFrontWarningScenario.java index df2adcc441..6de3fb5893 100644 --- a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/scenario/scene/warning/V2XFrontWarningScenario.java +++ b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/v2n/scenario/scene/warning/V2XFrontWarningScenario.java @@ -29,6 +29,7 @@ import com.mogo.eagle.core.utilcode.mogo.logger.CallerLogger; import com.mogo.eagle.function.biz.v2x.v2n.utils.V2XEventAnalyticsManager; import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.Locale; import java.util.concurrent.TimeUnit; @@ -68,7 +69,7 @@ public class V2XFrontWarningScenario extends AbsV2XScenario implements IMoGoChas if (mMarkerEntity != null) { CallerLogger.d(M_V2X + TAG, "----- show --- 2 --:\n" + mMarkerEntity); String v2xType = getV2XTypeForFrontWarning(mMarkerEntity); - V2XMessageEntity entity = getV2XMessageEntity(); +// V2XMessageEntity entity = getV2XMessageEntity(); if (!v2xType.equals("0")) { if (getAlertContentForFrontWarning(mMarkerEntity).toString() == null || getAlertContentForFrontWarning(mMarkerEntity).toString().isEmpty() @@ -112,8 +113,8 @@ public class V2XFrontWarningScenario extends AbsV2XScenario implements IMoGoChas private CharSequence getAlertContentForFrontWarning(V2XWarningTarget entity) { double dis = entity.getDistance(); //距离四舍五入保留整数 - BigDecimal bg = new BigDecimal(dis); - double disBig = bg.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue(); + BigDecimal bg = BigDecimal.valueOf(dis); + double disBig = bg.setScale(0, RoundingMode.HALF_UP).doubleValue(); String distance = String.format(Locale.getDefault(), "%.0f", disBig) + "米"; String content = entity.getWarningContent(); SpannableStringBuilder ssb = new SpannableStringBuilder(content + distance); diff --git a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/vip/VipCarManager.kt b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/vip/VipCarManager.kt index f8b8b54b48..dce13bd7be 100644 --- a/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/vip/VipCarManager.kt +++ b/core/function-impl/mogo-core-function-biz/src/main/java/com/mogo/eagle/function/biz/v2x/vip/VipCarManager.kt @@ -4,7 +4,6 @@ import android.content.Context import android.os.Handler import android.os.Looper import android.os.Message -import android.util.Log import com.mogo.aicloud.services.socket.IMogoOnMessageListener import com.mogo.aicloud.services.socket.MogoAiCloudSocketManager import com.mogo.cloud.passport.MoGoAiCloudClientConfig @@ -269,9 +268,6 @@ class VipCarManager : IMogoOnMessageListener, IMoGoTrafficLightListe alertContent: CharSequence, ttsContent: String, ) { - if (alertContent.toString().isEmpty() || ttsContent.isEmpty()) { - Log.d("MsgBox-VipCarManager", "alertContent或ttsContent为空!") - } CallerMsgBoxManager.saveMsgBox( MsgBoxBean(MsgBoxType.V2X, V2XMsg(v2xType, alertContent.toString(), ttsContent,CommunicationType.V2N.name)) ) diff --git a/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/MoGoAutopilotControlProvider.kt b/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/MoGoAutopilotControlProvider.kt index 5450a5e2c7..9a8bb01c9e 100644 --- a/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/MoGoAutopilotControlProvider.kt +++ b/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/MoGoAutopilotControlProvider.kt @@ -21,7 +21,7 @@ import com.mogo.eagle.core.data.deva.chain.ChainConstant import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_CODE_ADAS_SEND import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_CODE_MULTI_CONNECT import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_SOURCE_ADAS -import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_INIT_STATUS +import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_STATUS import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_SOCKET_AUTOPILOT import com.mogo.eagle.core.function.api.autopilot.IMoGoAutopilotCarConfigListener import com.mogo.eagle.core.function.api.autopilot.IMoGoAutopilotControlProvider @@ -347,7 +347,7 @@ class MoGoAutopilotControlProvider : startAutoPilot(controlParameters, Constants.AUTOPILOT_SOURCE.PAD) } - //todo chainlog + //todo emArrow chainlog override fun startAutoPilotByMoFang(controlParameters: AutopilotControlParameters?) { if (controlParameters==null){ startAutoPilotWithNoParameter(Constants.AUTOPILOT_SOURCE.MO_FANG) @@ -983,7 +983,7 @@ class MoGoAutopilotControlProvider : } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_ADAS, nodeAliasCode = CHAIN_CODE_MULTI_CONNECT, paramIndexes = [0] diff --git a/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/adapter/MoGoAdasListenerImpl.kt b/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/adapter/MoGoAdasListenerImpl.kt index 0263d37654..ceb751d72d 100644 --- a/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/adapter/MoGoAdasListenerImpl.kt +++ b/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/adapter/MoGoAdasListenerImpl.kt @@ -23,7 +23,7 @@ import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_CODE_AD import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_CODE_ADAS_STATUS_QUERY_RESP import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_SOURCE_ADAS import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_GNSS -import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_INIT_STATUS +import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_STATUS import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_SOCKET_AUTOPILOT import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_SOCKET_TRAJECTORY import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_SOCKET_VEHICLE @@ -50,7 +50,6 @@ import com.mogo.eagle.core.function.call.obu.CallerObuMapMathListenerManager import com.mogo.eagle.core.function.call.obu.CallerObuWarningRsiListenerManager import com.mogo.eagle.core.function.call.obu.CallerObuWarningRsmListenerManager import com.mogo.eagle.core.function.call.obu.CallerObuWarningSpatListenerManager -import com.mogo.eagle.core.function.call.v2x.* import com.mogo.eagle.core.utilcode.mogo.logger.Logger import com.mogo.eagle.core.utilcode.util.DeviceUtils import com.mogo.support.obu.ObuScene @@ -364,7 +363,7 @@ class MoGoAdasListenerImpl : OnAdasListener { //工控机基础配置信息 @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_ADAS, nodeAliasCode = CHAIN_CODE_ADAS_CAR_CONFIG, paramIndexes = [0, 1] diff --git a/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/telematic/TeleMsgHandler.kt b/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/telematic/TeleMsgHandler.kt index 1b55e0fd3a..cbac9fcb20 100644 --- a/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/telematic/TeleMsgHandler.kt +++ b/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/autopilot/telematic/TeleMsgHandler.kt @@ -9,7 +9,7 @@ import com.mogo.eagle.core.data.biz.trafficlight.TrafficLightResult import com.mogo.eagle.core.data.config.FunctionBuildConfig import com.mogo.eagle.core.data.config.HmiBuildConfig import com.mogo.eagle.core.data.deva.chain.ChainConstant -import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_INIT_STATUS +import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_STATUS import com.mogo.eagle.core.data.multidisplay.TelematicConstant import com.mogo.eagle.core.function.call.autopilot.CallerAutoPilotControlManager import com.mogo.eagle.core.function.call.autopilot.CallerAutoPilotControlManager.setDemoMode @@ -65,7 +65,7 @@ class TeleMsgHandler : IMsgHandler { AdasManager.getInstance().decoderRaw(it.body) } catch (e: Exception) { e.printStackTrace() - invokeNettyConnResult("乘客屏解析数据过程中出现异常:${e.message}") + invokeReqStatusLog(mapOf("dataParseError" to "${e.message}")) } } MogoProtocolMsg.SYNC_MODE_STATUS -> { @@ -188,8 +188,8 @@ class TeleMsgHandler : IMsgHandler { MogoProtocolMsg.REQ_MAC_ADDRESS, configArray.size, configArray ), channel - ) { - invokeNettyConnResult("司机屏发送配置信息到乘客屏是否成功:${it.isSuccess}") + ) { future -> + invokeReqStatusLog(mapOf("dSendParam2P" to future.isSuccess)) } } else { queryCarConfig() @@ -205,8 +205,8 @@ class TeleMsgHandler : IMsgHandler { val snArray = sn.toByteArray() NSDNettyManager.getInstance().sendMsgToSpecifiedClient( MogoProtocolMsg(10, snArray.size, snArray), channel - ) { - invokeNettyConnResult("司机屏发送SN(${sn})到乘客屏是否成功:${it.isSuccess}") + ) { future -> + invokeReqStatusLog(mapOf("dSendSN(${sn})2P" to future.isSuccess)) } } else { invokeNettyConnResult("司机屏SN未获取到,不发送给乘客屏") @@ -245,12 +245,12 @@ class TeleMsgHandler : IMsgHandler { } // AdasManager.getInstance().startDispatchHandler() ToastUtils.showShort("连接司机屏成功!") - invokeNettyConnResult("乘客屏连接司机屏成功") + invokeReqStatusLog(mapOf("dpConnectStatus" to true)) val byteArray = byteArrayOf(0) NSDNettyManager.getInstance().sendMogoProtocolMsgToServer( MogoProtocolMsg(MogoProtocolMsg.REQ_MAC_ADDRESS, byteArray.size, byteArray) ) { - invokeNettyConnResult("乘客屏请求配置信息的数据发送是否成功:${it}") + invokeReqStatusLog(mapOf("pReqParamSendResult" to it)) } // 请求司机屏SN reqServerSN() @@ -261,14 +261,14 @@ class TeleMsgHandler : IMsgHandler { AppConfigInfo.plateNumber = "" AppConfigInfo.iPCMacAddress = "" ToastUtils.showLong("断开和司机屏的连接!") - invokeNettyConnResult("断开和司机屏的连接!") + invokeReqStatusLog(mapOf("dpConnectStatus" to false)) AdasManager.getInstance().stopDispatchHandler() } } ConnectState.STATUS_CONNECT_ERROR -> { AppConfigInfo.plateNumber = "" ToastUtils.showLong("和司机端连接异常!") - invokeNettyConnResult("乘客屏和司机屏连接异常,错误为:$content") + invokeReqStatusLog(mapOf("dpConnectErrorMsg" to "$content")) AdasManager.getInstance().stopDispatchHandler() } else -> { @@ -280,7 +280,7 @@ class TeleMsgHandler : IMsgHandler { override fun handleServerConnStatus(statusCode: Int, content: String?, channel: Channel) {} @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = ChainConstant.CHAIN_SOURCE_ADAS, nodeAliasCode = ChainConstant.CHAIN_CODE_MULTI_CONNECT, paramIndexes = [0] @@ -289,6 +289,16 @@ class TeleMsgHandler : IMsgHandler { CallerLogger.d("${SceneConstant.M_D_C}$TAG", status) } + @ChainLog( + linkChainLog = CHAIN_TYPE_STATUS, + linkCode = ChainConstant.CHAIN_SOURCE_ADAS, + nodeAliasCode = ChainConstant.CHAIN_CODE_MULTI_CONNECT, + paramIndexes = [0] + ) + private fun invokeReqStatusLog(param:Map){ + CallerLogger.d("${SceneConstant.M_D_C}$TAG", param.toString()) + } + /** * 记录最新的司机屏发送数据的时间戳 * 或乘客屏解析数据的时间戳 @@ -317,7 +327,7 @@ class TeleMsgHandler : IMsgHandler { NSDNettyManager.getInstance().sendMogoProtocolMsgToServer( MogoProtocolMsg(10, byteArray.size, byteArray) ) { - invokeNettyConnResult("乘客屏请求司机屏SN的数据发送是否成功:${it}") + invokeReqStatusLog(mapOf("pReqSNSendResult" to it)) } delay(700) } diff --git a/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/v2x/SpeedLimitDispatcher.kt b/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/v2x/SpeedLimitDispatcher.kt index 0346113ae1..639072fbfa 100644 --- a/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/v2x/SpeedLimitDispatcher.kt +++ b/core/function-impl/mogo-core-function-datacenter/src/main/java/com/mogo/eagle/core/function/datacenter/v2x/SpeedLimitDispatcher.kt @@ -31,7 +31,7 @@ class SpeedLimitDispatcher : ILimitingVelocityListener { /** * 地图限速数据 */ -// @BizConfig(FuncBizConfig.V2I, "", FuncBizConfig.BIZ_SLW) //todo arrow 重新考虑放的位置 +// @BizConfig(FuncBizConfig.V2I, "", FuncBizConfig.BIZ_SLW) //todo emArrow 重新考虑放的位置 override fun onUnion(limitingVelocity: Int, sourceType: DataSourceType) { super.onUnion(limitingVelocity, sourceType) when (sourceType) { // obu 优先级高于 map,体现链路能力 diff --git a/core/function-impl/mogo-core-function-devatools/src/main/AndroidManifest.xml b/core/function-impl/mogo-core-function-devatools/src/main/AndroidManifest.xml index b0de6b5f86..56b7521c8a 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/AndroidManifest.xml +++ b/core/function-impl/mogo-core-function-devatools/src/main/AndroidManifest.xml @@ -8,4 +8,5 @@ + \ No newline at end of file diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/DevaToolsProvider.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/DevaToolsProvider.kt index 8c4130608a..dbe66b0d48 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/DevaToolsProvider.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/DevaToolsProvider.kt @@ -173,7 +173,7 @@ class DevaToolsProvider : IDevaToolsProvider { if (plugin is TracePlugin) { if (tag == SharePluginInfo.TAG_PLUGIN_EVIL_METHOD) { isEvil = true - printEvilMsg(issue.toString()) + printEvilMsg(mapOf("evilMethod" to issue.toString())) } } } @@ -216,7 +216,7 @@ class DevaToolsProvider : IDevaToolsProvider { nodeAliasCode = ChainConstant.CHAIN_CODE_RECORD_ANR, paramIndexes = [0] ) - private fun printEvilMsg(evilMethod: String) { + private fun printEvilMsg(evilMethod: Map) { w("TraceCanary", evilMethod) } diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/apm/ApmEnvProviderImpl.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/apm/ApmEnvProviderImpl.kt index 65a2c104ac..d9e3bc01e4 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/apm/ApmEnvProviderImpl.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/apm/ApmEnvProviderImpl.kt @@ -6,7 +6,7 @@ import android.widget.Toast import com.mogo.commons.debug.DebugConfig import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_CODE_INIT_ENV_RESTART import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_SOURCE_INIT -import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_INIT_STATUS +import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_STATUS import com.mogo.eagle.core.function.api.devatools.apm.* import com.mogo.eagle.core.utilcode.util.* import com.zhjt.mogo_core_function_devatools.apm.config.* @@ -84,7 +84,7 @@ class ApmEnvProviderImpl: IApmEnvProvider, CoroutineScope { val appRelaunched = ApmEnvConfig.isAppRelaunched() if ((!isEnvValid || (buildTypeChanged || netTypeChanged || dockerVersionChanged)) && !appRelaunched) { ApmEnvConfig.setAppRelaunched(true) - restartApp("buildType:$buildType,netType:$netType,dockerVersion:$dockerVersion") + restartApp(mapOf("buildType" to buildType, "netType" to netType,"dockerVersion" to dockerVersion)) return@launch } if (isFirstDockerVersionSet) { @@ -110,12 +110,12 @@ class ApmEnvProviderImpl: IApmEnvProvider, CoroutineScope { } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_INIT, nodeAliasCode = CHAIN_CODE_INIT_ENV_RESTART, paramIndexes = [0] ) - private fun restartApp(envStr:String) { + private fun restartApp(envStr:Map) { launch(Dispatchers.Main) { Toast.makeText(Utils.getApp(), "发现系统环境不一致,正在重启...", Toast.LENGTH_SHORT).show() delay(50) diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/CaseTopicListDialog.java b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/CaseTopicListDialog.java index ea8ae41b25..b924f6213a 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/CaseTopicListDialog.java +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/CaseTopicListDialog.java @@ -48,10 +48,10 @@ public class CaseTopicListDialog extends Dialog implements IMoGoAutopilotRecordL private RecyclerView rvTopicList; private TopicListAdapter topicListAdapter; private String searchStr; - private List allTopicList = new ArrayList<>(); + private final List allTopicList = new ArrayList<>(); private RecordTypeEntity recordType; - private List addTopicList = new ArrayList<>(); - private List searchTopicList = new ArrayList<>(); + private final List addTopicList = new ArrayList<>(); + private final List searchTopicList = new ArrayList<>(); public CaseTopicListDialog(@NonNull Context context) { super(context, R.style.bad_case_dialog); diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/adapter/CaseListAdapter.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/adapter/CaseListAdapter.kt index 8e211749b0..ed86507820 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/adapter/CaseListAdapter.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/adapter/CaseListAdapter.kt @@ -13,7 +13,7 @@ import com.zhjt.mogo_core_function_devatools.R * @description Case清单列表适配器 * @since: 2022/10/19 */ -class CaseListAdapter: RecyclerView.Adapter() { +open class CaseListAdapter: RecyclerView.Adapter() { private var data:List? = null private var caseClickListener: CaseClickListener?=null diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/adapter/TopicListAdapter.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/adapter/TopicListAdapter.kt index 33bb3ff608..e107e18b89 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/adapter/TopicListAdapter.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/biz/adapter/TopicListAdapter.kt @@ -13,7 +13,7 @@ import com.zhjt.mogo_core_function_devatools.R * @description Topic列表适配器 * @since: 2022/10/19 */ -class TopicListAdapter: RecyclerView.Adapter() { +open class TopicListAdapter: RecyclerView.Adapter() { private var data:MutableList? = null private var topicClickListener: TopicClickListener? = null diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/Audition.java b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/Audition.java index f4ec60ac13..9de418509a 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/Audition.java +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/Audition.java @@ -6,14 +6,12 @@ import android.text.TextUtils; //播放试听 public class Audition implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener{ - private static volatile Audition INSTANCE; public MediaPlayer mediaPlayer; private String oldPath; private OnAuditionListener listener; public interface OnAuditionListener { void onAuditionCompletion(); - } public void registerOnAuditionListener(OnAuditionListener listener) { @@ -28,16 +26,12 @@ public class Audition implements MediaPlayer.OnPreparedListener, MediaPlayer.OnC } public static Audition getInstance() { - if (INSTANCE == null) { - synchronized (Audition.class) { - if (INSTANCE == null) { - INSTANCE = new Audition(); - } - } - } - return INSTANCE; + return Holder.INSTANCE; } + private static final class Holder{ + private static final Audition INSTANCE = new Audition(); + } public boolean isPlaying() { return mediaPlayer != null && mediaPlayer.isPlaying(); diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/RecordHelper.java b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/RecordHelper.java index d7a33d08ae..e7f3875873 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/RecordHelper.java +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/RecordHelper.java @@ -5,7 +5,6 @@ import static com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant.M_DEV import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Environment; -import android.util.Log; import com.mogo.eagle.core.utilcode.mogo.logger.CallerLogger; import com.mogo.eagle.core.utilcode.util.FileUtils; @@ -42,7 +41,7 @@ public class RecordHelper { private File resultFile = null; private File tmpFile = null; - private List files = new ArrayList<>(); + private final List files = new ArrayList<>(); private Mp3EncodeThread mp3EncodeThread; public RecordHelper(RecordConfig config) { @@ -69,7 +68,9 @@ public class RecordHelper { return; } String path = getFilePath(fileName); - resultFile = new File(path); + if(path!=null){ + resultFile = new File(path); + } String tempFilePath = getTempFilePath(); tmpFile = new File(tempFilePath); audioRecordThread = new AudioRecordThread(); @@ -134,7 +135,7 @@ public class RecordHelper { } } - private FftFactory fftFactory = new FftFactory(FftFactory.Level.Original); + private final FftFactory fftFactory = new FftFactory(FftFactory.Level.Original); private void notifyData(final byte[] data) { if (listener != null) { @@ -192,14 +193,10 @@ public class RecordHelper { @Override public void run() { super.run(); - - switch (currentConfig.getFormat()) { - case MP3: - startMp3Recorder(); - break; - default: - startPcmRecorder(); - break; + if (currentConfig.getFormat() == RecordConfig.RecordFormat.MP3) { + startMp3Recorder(); + } else { + startPcmRecorder(); } } @@ -275,12 +272,9 @@ public class RecordHelper { private void stopMp3Encoded() { if (mp3EncodeThread != null) { - mp3EncodeThread.stopSafe(new Mp3EncodeThread.EncordFinishListener() { - @Override - public void onFinish() { - notifyFinish(); - mp3EncodeThread = null; - } + mp3EncodeThread.stopSafe(() -> { + notifyFinish(); + mp3EncodeThread = null; }); } else { CallerLogger.e("$M_DEVA$TAG", "mp3EncodeThread is null, 代码业务流程有误,请检查!! "); @@ -382,8 +376,7 @@ public class RecordHelper { } String format = currentConfig.getFormat().getExtension(); - String filePath = String.format(Locale.getDefault(), "%s%s%s", ROOT_PATH, fileName, format); - return filePath; + return String.format(Locale.getDefault(), "%s%s%s", ROOT_PATH, fileName, format); } private String getTempFilePath() { diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/RecordManager.java b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/RecordManager.java index a8a167bb27..b4ec2edc7a 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/RecordManager.java +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/badcase/record/RecordManager.java @@ -7,9 +7,7 @@ import com.zhjt.mogo_core_function_devatools.badcase.record.listener.RecordListe public class RecordManager { - private static final String TAG = RecordManager.class.getSimpleName(); @SuppressLint("StaticFieldLeak") - private volatile static RecordManager instance; private final RecordHelper recordHelper; /** * 录音配置 @@ -21,14 +19,11 @@ public class RecordManager { } public static RecordManager getInstance() { - if (instance == null) { - synchronized (RecordManager.class) { - if (instance == null) { - instance = new RecordManager(); - } - } - } - return instance; + return Holder.instance; + } + + private static final class Holder{ + private static final RecordManager instance = new RecordManager(); } // /** diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/binding/BindingCarManager.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/binding/BindingCarManager.kt index 9b93806824..6d75602abd 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/binding/BindingCarManager.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/binding/BindingCarManager.kt @@ -3,7 +3,6 @@ package com.zhjt.mogo_core_function_devatools.binding import android.annotation.* import android.content.Context import android.text.TextUtils -import com.elegant.utils.UiThreadHandler import com.mogo.cloud.passport.MoGoAiCloudClientConfig import com.mogo.commons.constants.SharedPrefsConstants import com.mogo.eagle.core.data.app.AppConfigInfo.role @@ -25,7 +24,6 @@ import com.zhjt.mogo_core_function_devatools.upgrade.UpgradeAppNetWorkManager import mogo.telematics.pad.MessagePad /** - * //todo emArrow 链路biz * 车辆绑定 */ @SuppressLint("StaticFieldLeak") diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/binding/BindingCarNetWorkManager.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/binding/BindingCarNetWorkManager.kt index 3a0b9d64d3..778cc13a1e 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/binding/BindingCarNetWorkManager.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/binding/BindingCarNetWorkManager.kt @@ -8,6 +8,7 @@ import com.mogo.eagle.core.data.deva.bindingcar.BindingCarInfo import com.mogo.eagle.core.data.deva.bindingcar.BindingCarRequest import com.mogo.eagle.core.data.deva.bindingcar.ModifyBindingcarInfo import com.mogo.eagle.core.data.config.HdMapBuildConfig +import com.mogo.eagle.core.data.deva.chain.ChainConstant import com.mogo.eagle.core.function.call.hmi.CallerHmiManager.showBindingCarDialog import com.mogo.eagle.core.function.call.hmi.CallerHmiManager.showModifyBindingCarDialog import com.mogo.eagle.core.function.call.map.CallerMapUIServiceManager @@ -20,6 +21,7 @@ import com.mogo.eagle.core.utilcode.mogo.storage.SharedPrefsMgr import com.mogo.eagle.core.utilcode.mogo.toast.TipToast import com.mogo.eagle.core.utilcode.util.GsonUtils import com.zhjt.mogo_core_function_devatools.R +import com.zhjt.service.chain.ChainLog import io.reactivex.Observer import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable @@ -65,6 +67,7 @@ class BindingCarNetWorkManager private constructor() { MediaType.get("application/json;charset=UTF-8"), GsonUtil.jsonFromObject(request) ) + bindLog(mapOf("bingReq" to request)) mBindingCarApiService.getBindingCarInfo(requestBody) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) @@ -72,7 +75,7 @@ class BindingCarNetWorkManager private constructor() { override fun onSubscribe(d: Disposable) {} override fun onNext(info: BindingCarInfo) { if (info != null && info.getData() != null) { - d(SceneConstant.M_DEVA + TAG, "getBindingCarInfo data =" + info.getData().toString() + "---getDefaultId() : ${getDefaultId()}") + bindLog(mapOf("bindResult" to true,"carType" to getDefaultId(),"msg" to info)) SharedPrefsMgr.getInstance(context).putString( SharedPrefsConstants.CAR_INFO, GsonUtils.toJson(info.getData()) @@ -91,6 +94,7 @@ class BindingCarNetWorkManager private constructor() { override fun onError(e: Throwable) { SharedPrefsMgr.getInstance(context).putString(SharedPrefsConstants.CAR_INFO, "") + bindLog(mapOf("bindResult" to false,"msg" to e.toString())) e(SceneConstant.M_DEVA + TAG, "getBindingCarInfo onError e = " + e.toString() + "---e.getMessage = " + e.message + "---getDefaultId() : ${getDefaultId()}") } @@ -115,6 +119,7 @@ class BindingCarNetWorkManager private constructor() { widevineIDWithMd5, screenType ) + bindLog(mapOf("bindingReq" to request)) val requestBody = RequestBody.create( MediaType.get("application/json;charset=UTF-8"), GsonUtil.jsonFromObject(request) @@ -127,13 +132,13 @@ class BindingCarNetWorkManager private constructor() { override fun onNext(info: ModifyBindingcarInfo) { if (info != null) { callBack.invoke(info) - d(SceneConstant.M_DEVA + TAG, "modifyBindingCar onNext code = " + info.code + "---msg = " + info.msg + "--info.toString() = " + info.toString()) + bindLog(mapOf("bindingStatus" to true,"bindMsg" to info)) updateCarVrIconRes(info.data.brandId) } } override fun onError(e: Throwable) { - e(SceneConstant.M_DEVA + TAG, "modifyBindingCar onError e = " + e.toString() + "---e.getMessage = " + e.message) + bindLog(mapOf("bindingStatus" to false,"bindMsg" to e.toString())) } override fun onComplete() {} @@ -177,6 +182,16 @@ class BindingCarNetWorkManager private constructor() { } } + @ChainLog( + linkChainLog = ChainConstant.CHAIN_TYPE_STATUS, + linkCode = ChainConstant.CHAIN_SOURCE_INIT, + nodeAliasCode = ChainConstant.CHAIN_CODE_BINDING_CAR, + paramIndexes = [0] + ) + private fun bindLog(msg:Map){ + d(SceneConstant.M_DEVA + TAG, "bindLog : $msg") + } + private fun getDefaultId(): String { return when (HdMapBuildConfig.currentCarVrIconRes) { R.raw.chuzuche -> "1" diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/block/MainBlockLinkedLog.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/block/MainBlockLinkedLog.kt index 6cbb66cf99..eea4d563f0 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/block/MainBlockLinkedLog.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/block/MainBlockLinkedLog.kt @@ -14,7 +14,7 @@ internal class MainBlockLinkedLog { } @ChainLog( - linkChainLog = ChainConstant.CHAIN_TYPE_HMI, + linkChainLog = ChainConstant.CHAIN_TYPE_ANR_LEAK, linkCode = ChainConstant.CHAIN_SOURCE_HMI, nodeAliasCode = ChainConstant.CHAIN_CODE_MAIN_BLOCK, paramIndexes = [0] diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/funcconfig/FuncConfigCenter.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/funcconfig/FuncConfigCenter.kt index efdd65d59b..1ab4a727c3 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/funcconfig/FuncConfigCenter.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/funcconfig/FuncConfigCenter.kt @@ -6,7 +6,7 @@ import com.mogo.aicloud.services.socket.MogoAiCloudSocketManager import com.mogo.commons.AbsMogoApplication import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_CODE_FUNC_CONFIG_CHANGED import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_SOURCE_CLOUD -import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_INIT_STATUS +import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_STATUS import com.mogo.eagle.core.function.api.autopilot.IMoGoAutopilotCarConfigListener import com.mogo.eagle.core.function.call.autopilot.CallerAutopilotCarConfigListenerManager import com.mogo.eagle.core.function.call.devatools.CallerDevaToolsFuncConfigListenerManager @@ -71,7 +71,7 @@ class FuncConfigCenter : IMogoOnMessageListener, IMoGoAutopilotCarCo } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, nodeAliasCode = CHAIN_CODE_FUNC_CONFIG_CHANGED, paramIndexes = [0] diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/mofang/MoFangLinkedLog.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/mofang/MoFangLinkedLog.kt index 5018c98c57..4c3354d0cd 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/mofang/MoFangLinkedLog.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/mofang/MoFangLinkedLog.kt @@ -14,7 +14,7 @@ internal class MoFangLinkedLog { } @ChainLog( - linkChainLog = ChainConstant.CHAIN_TYPE_HMI, + linkChainLog = ChainConstant.CHAIN_TYPE_STATUS, linkCode = ChainConstant.CHAIN_SOURCE_HMI, nodeAliasCode = ChainConstant.CHAIN_CODE_MO_FANG_CONNECT, paramIndexes = [0] diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/monitor/remote/RemoteUserServiceImp.java b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/monitor/remote/RemoteUserServiceImp.java index d9f1d3487a..8ca36552ad 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/monitor/remote/RemoteUserServiceImp.java +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/monitor/remote/RemoteUserServiceImp.java @@ -60,8 +60,10 @@ public class RemoteUserServiceImp extends Binder implements IUserInterface { String _arg0; _arg0 = data.readString(); String _result = this.exec(_arg0); - reply.writeNoException(); - reply.writeString(_result); + if (reply != null) { + reply.writeNoException(); + reply.writeString(_result); + } return true; default: return super.onTransact(code, data, reply, flags); diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/scene/SceneManager.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/scene/SceneManager.kt index 71dec64930..d46fb86471 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/scene/SceneManager.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/scene/SceneManager.kt @@ -49,7 +49,7 @@ class SceneManager { //过滤所需条件 sceneModuleTAG.map[ADAS] = SceneModule(true, M_D_C) sceneModuleTAG.map[DEVA] = SceneModule(true, M_DEVA) - sceneModuleTAG.map[HMI] = SceneModule(false, M_HMI) + sceneModuleTAG.map[HMI] = SceneModule(true, M_HMI) sceneModuleTAG.map[OBU] = SceneModule(true, M_OBU) sceneModuleTAG.map[V2X] = SceneModule(true, M_V2X) sceneModuleTAG.map[MAP] = SceneModule(true, M_MAP) diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/trace/SyncConfig.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/trace/SyncConfig.kt index e5464fd9d1..da26ec4642 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/trace/SyncConfig.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/trace/SyncConfig.kt @@ -51,7 +51,7 @@ object SyncConfig { } @ChainLog( - linkChainLog = ChainConstant.CHAIN_TYPE_INIT_STATUS, + linkChainLog = ChainConstant.CHAIN_TYPE_STATUS, linkCode = ChainConstant.CHAIN_SOURCE_INIT, nodeAliasCode = ChainConstant.CHAIN_CODE_APP_INFO_CONFIG_UPDATE, paramIndexes = [0] diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/trace/TraceManager.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/trace/TraceManager.kt index ecf880c9c6..0f53e12065 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/trace/TraceManager.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/trace/TraceManager.kt @@ -3,7 +3,6 @@ package com.zhjt.mogo_core_function_devatools.trace import android.content.Context import android.os.Handler import android.os.Looper -import com.mogo.cloud.passport.MoGoAiCloudClientConfig import com.mogo.eagle.core.data.deva.chain.ChainConstant import com.mogo.eagle.core.data.deva.chain.ChainLogParam import com.mogo.eagle.core.function.api.autopilot.IMoGoAutopilotCarConfigListener @@ -58,7 +57,7 @@ class TraceManager : IMoGoCloudListener, IMoGoAutopilotCarConfigListener { CallerAutopilotCarConfigListenerManager.addListener(TAG, this) // Trace过程中进行日志抓取,对日志进行配置 - fwBuildMap[ChainConstant.CHAIN_TYPE_INIT_STATUS] = + fwBuildMap[ChainConstant.CHAIN_TYPE_STATUS] = FwBuild(true, -1, pkgName + ChainConstant.CHAIN_LINK_LOG_INIT) fwBuildMap[ChainConstant.CHAIN_TYPE_GNSS] = FwBuild(true, -1, pkgName + ChainConstant.CHAIN_LINK_LOG_ADAS_GNSS) @@ -72,8 +71,6 @@ class TraceManager : IMoGoCloudListener, IMoGoAutopilotCarConfigListener { FwBuild(false, 30, pkgName + ChainConstant.CHAIN_LINK_LOG_ADAS_VEHICLE) fwBuildMap[ChainConstant.CHAIN_TYPE_SOCKET_TRAFFIC_LIGHT] = FwBuild(true, -1, pkgName + ChainConstant.CHAIN_LINK_LOG_ADAS_TRAFFIC_LIGHT) - fwBuildMap[ChainConstant.CHAIN_TYPE_HMI] = - FwBuild(true, -1, pkgName + ChainConstant.CHAIN_LINK_LOG_HMI_ACTIONS) fwBuildMap[ChainConstant.CHAIN_TYPE_ANR_LEAK] = FwBuild(true, -1, pkgName + ChainConstant.CHAIN_LINK_LOG_RECORD_ANR) fwBuildMap[ChainConstant.CHAIN_TYPE_V2X] = @@ -86,7 +83,7 @@ class TraceManager : IMoGoCloudListener, IMoGoAutopilotCarConfigListener { FwBuild(true, -1, pkgName + ChainConstant.CHAIN_LINK_LOG_OCH) - traceInfoCache[ChainConstant.CHAIN_TYPE_INIT_STATUS] = + traceInfoCache[ChainConstant.CHAIN_TYPE_STATUS] = ChainLogParam(true, "INIT状态") traceInfoCache[ChainConstant.CHAIN_TYPE_GNSS] = ChainLogParam(true, "ADAS自车定位") @@ -100,8 +97,6 @@ class TraceManager : IMoGoCloudListener, IMoGoAutopilotCarConfigListener { ChainLogParam(false, "ADAS车辆底盘数据") traceInfoCache[ChainConstant.CHAIN_TYPE_SOCKET_TRAFFIC_LIGHT] = ChainLogParam(true, "红绿灯Union数据") - traceInfoCache[ChainConstant.CHAIN_TYPE_HMI] = - ChainLogParam(true, "人机交互行为") traceInfoCache[ChainConstant.CHAIN_TYPE_ANR_LEAK] = ChainLogParam(true, "ANR Record") traceInfoCache[ChainConstant.CHAIN_TYPE_V2X] = @@ -156,7 +151,7 @@ class TraceManager : IMoGoCloudListener, IMoGoAutopilotCarConfigListener { fun refreshTraceInfo(map: HashMap) { map.forEach { (type, param) -> - if (type != ChainConstant.CHAIN_TYPE_INIT_STATUS) { + if (type != ChainConstant.CHAIN_TYPE_STATUS) { val fwBuild = this.fwBuildMap[type] fwBuild?.let { CallerLogger.d("$M_DEVA$TAG", "param : ${param.des} , record : ${param.record}") diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/upgrade/UpgradeManager.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/upgrade/UpgradeManager.kt index b0219909a7..cd1ac45a4a 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/upgrade/UpgradeManager.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/upgrade/UpgradeManager.kt @@ -29,7 +29,6 @@ import kotlinx.coroutines.* import java.io.IOException import java.util.concurrent.ConcurrentHashMap -//todo emArrow trace class UpgradeManager : IDownloadListener { companion object { diff --git a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/upgrade/provider/MoGoUpgradeProviderImpl.kt b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/upgrade/provider/MoGoUpgradeProviderImpl.kt index 2eece707f1..c0eaca9ef1 100644 --- a/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/upgrade/provider/MoGoUpgradeProviderImpl.kt +++ b/core/function-impl/mogo-core-function-devatools/src/main/java/com/zhjt/mogo_core_function_devatools/upgrade/provider/MoGoUpgradeProviderImpl.kt @@ -301,7 +301,7 @@ class MoGoUpgradeProviderImpl: IMoGoUpgradeProvider { @ChainLog( - linkChainLog = ChainConstant.CHAIN_TYPE_INIT_STATUS, + linkChainLog = ChainConstant.CHAIN_TYPE_STATUS, linkCode = ChainConstant.CHAIN_SOURCE_CLOUD, nodeAliasCode = ChainConstant.CHAIN_CODE_UPGRADE_APP, paramIndexes = [0] diff --git a/core/function-impl/mogo-core-function-hmi/src/main/AndroidManifest.xml b/core/function-impl/mogo-core-function-hmi/src/main/AndroidManifest.xml index 90ee278539..f3f3138647 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/AndroidManifest.xml +++ b/core/function-impl/mogo-core-function-hmi/src/main/AndroidManifest.xml @@ -54,14 +54,13 @@ --> @@ -97,21 +96,6 @@ - - - - - - - - - - - - - - - --> - - diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/notification/anim/DefaultAnimator.kt b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/notification/anim/DefaultAnimator.kt index d05fa0a36f..6b18a2f8ad 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/notification/anim/DefaultAnimator.kt +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/notification/anim/DefaultAnimator.kt @@ -3,11 +3,12 @@ package com.mogo.eagle.core.function.hmi.notification.anim import android.animation.Animator import android.animation.ValueAnimator import android.graphics.Rect -import android.util.Log import android.view.View import android.view.WindowManager import com.mogo.eagle.core.data.enums.SidePattern import com.mogo.eagle.core.function.hmi.notification.interfaces.OnFloatAnimator +import com.mogo.eagle.core.utilcode.mogo.logger.CallerLogger +import com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant.Companion.M_HMI import com.mogo.eagle.core.utilcode.util.BarUtils import kotlin.math.min @@ -52,7 +53,7 @@ open class DefaultAnimator : OnFloatAnimator { windowManager.updateViewLayout(view, params) } catch (e: Exception) { cancel() - Log.i("DebugViewSwitchLog", "执行动画异常,异常原因:"+e) + CallerLogger.i(M_HMI + "DebugViewSwitchLog", "执行动画异常,异常原因:$e") } } } diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/logcatch/LogItemAdapter.java b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/logcatch/LogItemAdapter.java index 36f3e02cd4..fdc64291f1 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/logcatch/LogItemAdapter.java +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/logcatch/LogItemAdapter.java @@ -249,11 +249,7 @@ public class LogItemAdapter extends AbsRecyclerAdapter, L protected void publishResults(CharSequence constraint, FilterResults results) { //noinspection unchecked mList = (List) results.values; - if (results.count > 0) { - notifyDataSetChanged(); - } else { - notifyDataSetChanged(); - } + notifyDataSetChanged(); } } } \ No newline at end of file diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/logcatch/LogLine.java b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/logcatch/LogLine.java index 8c858e6526..cf670d49ae 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/logcatch/LogLine.java +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/logcatch/LogLine.java @@ -25,6 +25,7 @@ public class LogLine { "\\): "); private static final String filterPattern = "ResourceType|memtrack|android.os.Debug|BufferItemConsumer|DPM.*|MDM.*|ChimeraUtils|BatteryExternalStats.*|chatty.*|DisplayPowerController|WidgetHelper|WearableService|DigitalWidget.*|^ANDR-PERF-.*"; + private static final String failPattern = "(^maxLineHeight.*)|(Failed to read.*)"; private int logLevel; private String tag; private String logOutput; @@ -57,7 +58,7 @@ public class LogLine { char logLevelChar = matcher.group(1).charAt(0); String logText = originalLine.substring(matcher.end()); - if (logText.matches("^maxLineHeight.*|Failed to read.*")) { + if (logText.matches(failPattern)) { logLine.setLogLevel(convertCharToLogLevel('V')); } else { logLine.setLogLevel(convertCharToLogLevel(logLevelChar)); diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/msgbox/SharpView.java b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/msgbox/SharpView.java index af4567c9dd..8261e641a1 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/msgbox/SharpView.java +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/msgbox/SharpView.java @@ -12,19 +12,18 @@ import androidx.annotation.Nullable; public class SharpView extends View { - private int mWidth =0; //三角形的宽度 - private int mHeight =0; //三角形的高度 - private Context mContext; + private int mWidth = 0; //三角形的宽度 + private int mHeight = 0; //三角形的高度 + private final Paint paint = new Paint(); + private final Path path = new Path(); public SharpView(Context context) { super(context); - this.mContext=context; initView(); } public SharpView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); - this.mContext=context; initView(); } @@ -32,28 +31,27 @@ public class SharpView extends View { mWidth = 25; mHeight = 25; } + @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); - setMeasuredDimension(mWidth,mHeight); + setMeasuredDimension(mWidth, mHeight); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //创建画笔 - Paint paint = new Paint(); paint.setColor(Color.parseColor("#FFFFFFFF")); paint.setAntiAlias(true); //抗锯齿 paint.setStyle(Paint.Style.FILL);//实线 //创建路径 - Path path = new Path(); - path.moveTo(0,mHeight); - path.lineTo(mWidth,mHeight); - path.lineTo(mWidth/2,0); + path.moveTo(0, mHeight); + path.lineTo(mWidth, mHeight); + path.lineTo(mWidth / 2.0f, 0); path.close();//闭合路径 //画在画布上 - canvas.drawPath(path,paint); + canvas.drawPath(path, paint); } } diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/notice/DispatchDialogManager.java b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/notice/DispatchDialogManager.java index 457a1682e9..28da7fc5d0 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/notice/DispatchDialogManager.java +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/notice/DispatchDialogManager.java @@ -5,6 +5,7 @@ import static com.mogo.eagle.core.data.biz.dispatch.DispatchAdasAutoPilotLocRece import static com.mogo.eagle.core.data.biz.dispatch.DispatchAdasAutoPilotLocReceiverBean.DISPATCH_TYPE_START; import static com.mogo.eagle.core.data.biz.dispatch.DispatchAdasAutoPilotLocReceiverBean.DISPATCH_TYPE_STOP; +import android.annotation.SuppressLint; import android.content.Context; import com.mogo.commons.voice.AIAssist; @@ -12,6 +13,7 @@ import com.mogo.eagle.core.data.biz.dispatch.DispatchAdasAutoPilotLocReceiverBea public class DispatchDialogManager { + @SuppressLint("StaticFieldLeak") private static volatile DispatchDialogManager manager; private static final byte[] obj = new byte[0]; private final Context mContext; diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/setting/DebugSettingView.kt b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/setting/DebugSettingView.kt index c3f19c6a35..798e21331a 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/setting/DebugSettingView.kt +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/setting/DebugSettingView.kt @@ -1311,11 +1311,9 @@ internal class DebugSettingView @JvmOverloads constructor( */ tbSelfLog.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { - LogUtils.getConfig().isLogSwitch = false Logger.init(LogLevel.OFF) MoGoAiCloudClient.getInstance().aiCloudClientConfig.isShowDebugLog = false } else { - LogUtils.getConfig().isLogSwitch = true Logger.init(LogLevel.DEBUG) MoGoAiCloudClient.getInstance().aiCloudClientConfig.isShowDebugLog = true } diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/setting/SOPSettingView.kt b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/setting/SOPSettingView.kt index e08857ad0c..a789e7e1da 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/setting/SOPSettingView.kt +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/setting/SOPSettingView.kt @@ -2,7 +2,6 @@ package com.mogo.eagle.core.function.hmi.ui.setting import android.content.Context import android.util.AttributeSet -import android.util.Log import android.view.LayoutInflater import android.view.View import android.widget.Toast @@ -84,24 +83,19 @@ internal class SOPSettingView @JvmOverloads constructor( scV2XSwitch.setOnCheckedChangeListener { _, isChecked -> FunctionBuildConfig.v2xMainSwitch = isChecked hmiAction("SOP V2X总开关, ",isChecked) - Log.i(TAG,"SOP V2X总开关,$isChecked") if(isChecked){ //V2N总开关 scV2NSwitch.isChecked = FunctionBuildConfig.v2nMainSwitch hmiAction("SOP V2N总开关, ",FunctionBuildConfig.v2nMainSwitch) - Log.i(TAG,"SOP V2N总开关, ${FunctionBuildConfig.v2nMainSwitch}") //V2I总开关 scV2ISwitch.isChecked = HmiBuildConfig.isShowObuV2iView hmiAction("SOP V2I总开关, ",HmiBuildConfig.isShowObuV2iView) - Log.i(TAG,"SOP V2I总开关, ${HmiBuildConfig.isShowObuV2iView}") //V2V总开关 scObuV2vView.isChecked = HmiBuildConfig.isShowObuV2vView hmiAction("SOP V2V总开关, ",HmiBuildConfig.isShowObuV2vView) - Log.i(TAG,"SOP V2V总开关, ${HmiBuildConfig.isShowObuV2vView}") //obu总开关 scObu.isChecked = obuConnectStatus hmiAction("SOP obu总开关, ",obuConnectStatus) - Log.i(TAG,"SOP obu总开关, $obuConnectStatus") if(obuConnectStatus){ CallerObuApiManager.resetObuIpAddress(MogoObuConst.OBU_DEFAULT_IP) } @@ -109,19 +103,15 @@ internal class SOPSettingView @JvmOverloads constructor( //V2N总开关 scV2NSwitch.isChecked = false hmiAction("SOP V2N总开关, ",false) - Log.i(TAG,"SOP V2N总开关, false") //V2I总开关 scV2ISwitch.isChecked = false hmiAction("SOP V2I总开关, ",false) - Log.i(TAG,"SOP V2I总开关, false") //V2V总开关 scObuV2vView.isChecked = false hmiAction("SOP V2V总开关, ",false) - Log.i(TAG,"SOP V2V总开关, false") //obu总开关 scObu.isChecked = false hmiAction("SOP OBU控制总开关, ",false) - Log.i(TAG,"SOP OBU控制总开关, false") //断开链接 CallerObuApiManager.disConnectObu() } @@ -145,31 +135,25 @@ internal class SOPSettingView @JvmOverloads constructor( //V2N新链路 scNewV2NData.isChecked = FunctionBuildConfig.isNewV2NData hmiAction("SOP 是否是V2N新链路(云->工控机->App)",FunctionBuildConfig.isNewV2NData) - Log.i(TAG,"SOP 是否是V2N新链路(云->工控机->App), ${FunctionBuildConfig.isNewV2NData}") //V2N场景进PNC scV2nPnc.isChecked = FunctionBuildConfig.isV2NPnc hmiAction("SOP V2N场景进PNC, ",FunctionBuildConfig.isV2NPnc) - Log.i(TAG,"SOP V2N场景进PNC, ${FunctionBuildConfig.isV2NPnc}") CallerAutoPilotControlManager.sendV2nToPncCmd(FunctionBuildConfig.isV2NPnc) //绿波通行 scGreenWaveSop.isChecked = HmiBuildConfig.isShowGreenWaveView hmiAction("SOP obu绿波通行, ",HmiBuildConfig.isShowGreenWaveView) - Log.i(TAG,"SOP obu绿波通行, ${HmiBuildConfig.isShowGreenWaveView}") CallerTelematicManager.sendMsgToAllClients(TelematicConstant.OBU_GREENWAVE_WARNING, "1".toByteArray()) }else{ //V2N新链路 scNewV2NData.isChecked = false hmiAction("SOP 是否是V2N新链路(云->工控机->App)",false) - Log.i(TAG,"SOP 是否是V2N新链路(云->工控机->App), false") //V2N场景进PNC scV2nPnc.isChecked = false hmiAction("SOP V2N场景进PNC, ",false) - Log.i(TAG,"SOP V2N场景进PNC, false") CallerAutoPilotControlManager.sendV2nToPncCmd(false) //绿波通行 scGreenWaveSop.isChecked = false hmiAction("SOP obu绿波通行, ",false) - Log.i(TAG,"SOP obu绿波通行, false") CallerTelematicManager.sendMsgToAllClients(TelematicConstant.OBU_GREENWAVE_WARNING, "0".toByteArray()) } scNewV2NData.isEnabled = isChecked @@ -192,32 +176,26 @@ internal class SOPSettingView @JvmOverloads constructor( //V2I场景进PNC scV2iPnc.isChecked = FunctionBuildConfig.isV2IPnc hmiAction("SOP V2I场景进PNC, ",FunctionBuildConfig.isV2IPnc) - Log.i(TAG,"SOP V2I场景进PNC,${FunctionBuildConfig.isV2IPnc}") CallerAutoPilotControlManager.sendV2iToPncCmd(FunctionBuildConfig.isV2IPnc) //闯红灯预警 scRunRedLightSop.isChecked = HmiBuildConfig.isShowRunRedLightView hmiAction("SOP obu闯红灯预警, ",HmiBuildConfig.isShowRunRedLightView) - Log.i(TAG,"SOP obu闯红灯预警, ${HmiBuildConfig.isShowRunRedLightView}") CallerTelematicManager.sendMsgToAllClients(TelematicConstant.OBU_RUNREDLIGHT_WARNING, "1".toByteArray()) //路侧弱势交通参与者 scObuWeaknessTrafficSop.isChecked = HmiBuildConfig.isShowObuWeaknessTrafficView hmiAction("SOP obu弱势交通控制, ",HmiBuildConfig.isShowObuWeaknessTrafficView) - Log.i(TAG,"SOP obu弱势交通控制, ${HmiBuildConfig.isShowObuWeaknessTrafficView}") }else{ //V2I场景进PNC scV2iPnc.isChecked = false CallerAutoPilotControlManager.sendV2iToPncCmd(false) hmiAction("SOP V2I场景进PNC, ",false) - Log.i(TAG,"SOP V2I场景进PNC, false") //闯红灯预警 scRunRedLightSop.isChecked = false hmiAction("SOP obu闯红灯预警, ",false) - Log.i(TAG,"SOP obu闯红灯预警, false") CallerTelematicManager.sendMsgToAllClients(TelematicConstant.OBU_RUNREDLIGHT_WARNING, "0".toByteArray()) //路侧弱势交通参与者 scObuWeaknessTrafficSop.isChecked = false hmiAction("SOP obu弱势交通控制, ",false) - Log.i(TAG,"SOP obu弱势交通控制, false") } scV2iPnc.isEnabled = isChecked scRunRedLightSop.isEnabled = isChecked @@ -235,7 +213,6 @@ internal class SOPSettingView @JvmOverloads constructor( return@setOnCheckedChangeListener } hmiAction("SOP 是否是V2N新链路(云->工控机->App)",isChecked) - Log.i(TAG,"SOP 是否是V2N新链路(云->工控机->App) ${isChecked}") FunctionBuildConfig.isNewV2NData = isChecked } @@ -246,7 +223,6 @@ internal class SOPSettingView @JvmOverloads constructor( return@setOnCheckedChangeListener } hmiAction("SOP V2N场景进PNC, ",isChecked) - Log.i(TAG,"SOP V2N场景进PNC, $isChecked") CallerAutoPilotControlManager.sendV2nToPncCmd(isChecked) FunctionBuildConfig.isV2NPnc = isChecked } @@ -258,7 +234,6 @@ internal class SOPSettingView @JvmOverloads constructor( return@setOnCheckedChangeListener } hmiAction("SOP obu绿波通行, ",isChecked) - Log.i(TAG,"SOP obu绿波通行, $isChecked") HmiBuildConfig.isShowGreenWaveView = isChecked if (HmiBuildConfig.isShowGreenWaveView) { CallerTelematicManager.sendMsgToAllClients(TelematicConstant.OBU_GREENWAVE_WARNING, "1".toByteArray()) @@ -274,7 +249,6 @@ internal class SOPSettingView @JvmOverloads constructor( return@setOnCheckedChangeListener } hmiAction("SOP V2I场景进PNC, ",isChecked) - Log.i(TAG,"SOP V2I场景进PNC, $isChecked") CallerAutoPilotControlManager.sendV2iToPncCmd(isChecked) FunctionBuildConfig.isV2IPnc = isChecked } @@ -286,7 +260,6 @@ internal class SOPSettingView @JvmOverloads constructor( return@setOnCheckedChangeListener } hmiAction("SOP obu闯红灯预警, ",isChecked) - Log.i(TAG,"SOP obu闯红灯预警, $isChecked") HmiBuildConfig.isShowRunRedLightView = isChecked if (HmiBuildConfig.isShowRunRedLightView) { CallerTelematicManager.sendMsgToAllClients(TelematicConstant.OBU_RUNREDLIGHT_WARNING, "1".toByteArray()) @@ -302,7 +275,6 @@ internal class SOPSettingView @JvmOverloads constructor( return@setOnCheckedChangeListener } hmiAction("SOP obu弱势交通控制, ",isChecked) - Log.i(TAG,"SOP obu弱势交通控制, $isChecked") HmiBuildConfig.isShowObuWeaknessTrafficView = isChecked } @@ -313,7 +285,6 @@ internal class SOPSettingView @JvmOverloads constructor( return@setOnCheckedChangeListener } hmiAction("SOP obuV2V开关, ",isChecked) - Log.i(TAG,"SOP obuV2V开关, $isChecked") HmiBuildConfig.isShowObuV2vView = isChecked } @@ -325,7 +296,6 @@ internal class SOPSettingView @JvmOverloads constructor( return@setOnCheckedChangeListener } hmiAction("SOP OBU控制总开关, ",isChecked) - Log.i(TAG,"SOP OBU控制总开关, $isChecked") if (isChecked) { CallerObuApiManager.resetObuIpAddress(MogoObuConst.OBU_DEFAULT_IP) } else { @@ -344,7 +314,6 @@ internal class SOPSettingView @JvmOverloads constructor( scMarkingObstacles.isChecked = FunctionBuildConfig.isPNCWarning scMarkingObstacles.setOnCheckedChangeListener { _, isChecked -> hmiAction("SOP 危险障碍物颜色标记开关, ",isChecked) - Log.i(TAG,"SOP 危险障碍物颜色标记开关, $isChecked") FunctionBuildConfig.isPNCWarning = isChecked } if (AppIdentityModeUtils.isBus(FunctionBuildConfig.appIdentityMode)) { @@ -355,7 +324,6 @@ internal class SOPSettingView @JvmOverloads constructor( scRouteDynamicEffect.isChecked = HmiBuildConfig.isShowRouteStrategy scRouteDynamicEffect.setOnCheckedChangeListener { _, isChecked -> hmiAction("SOP 引导线动态效果, ",isChecked) - Log.i(TAG,"SOP 引导线动态效果, $isChecked") HmiBuildConfig.isShowRouteStrategy = isChecked } @@ -378,7 +346,6 @@ internal class SOPSettingView @JvmOverloads constructor( CallerMapUIServiceManager.getMapUIController()?.setIsDrawPointCloud(isChecked) CallerSopSettingManager.invokePointCloudListener(isChecked) hmiAction("SOP 是否渲染点云数据, ",isChecked) - Log.i(TAG,"SOP 是否渲染点云数据, $isChecked") } //自车光圈 @@ -388,7 +355,6 @@ internal class SOPSettingView @JvmOverloads constructor( scCarAperture.isChecked = true CallerMapUIServiceManager.getMapUIController()?.setDisplayAnimEnable(true) hmiAction("SOP 是否展示自车光圈,",FunctionBuildConfig.isDisplayAnimEnable) - Log.i(TAG,"SOP 是否展示自车光圈,${FunctionBuildConfig.isDisplayAnimEnable}") }else{ scCarAperture.isChecked = FunctionBuildConfig.isDisplayAnimEnable } @@ -396,7 +362,6 @@ internal class SOPSettingView @JvmOverloads constructor( CallerMapUIServiceManager.getMapUIController()?.setDisplayAnimEnable(isChecked) CallerSopSettingManager.invokeCarApertureListener(isChecked) hmiAction("SOP 是否展示自车光圈,",isChecked) - Log.i(TAG,"SOP 是否展示自车光圈,$isChecked") if(!compoundButton.isPressed){ return@setOnCheckedChangeListener } @@ -412,7 +377,6 @@ internal class SOPSettingView @JvmOverloads constructor( scObstacleAvoidance.isChecked = FunctionBuildConfig.isDetouring scObstacleAvoidance.setOnCheckedChangeListener { _, isChecked -> hmiAction("SOP 绕障类功能开关, ",isChecked) - Log.i(TAG,"SOP 绕障类功能开关, $isChecked") CallerAutoPilotControlManager.sendDetouring(isChecked) FunctionBuildConfig.isDetouring = isChecked } @@ -424,7 +388,6 @@ internal class SOPSettingView @JvmOverloads constructor( return@setOnCheckedChangeListener } hmiAction("SOP 演示模式开关, ",!FunctionBuildConfig.isDemoMode) - Log.i(TAG,"SOP 演示模式开关, ${!FunctionBuildConfig.isDemoMode}") FunctionBuildConfig.isDemoMode = !FunctionBuildConfig.isDemoMode CallerAutoPilotControlManager.setDemoMode(FunctionBuildConfig.isDemoMode) CallerHmiViewControlListenerManager.invokeFuncMode(FUNC_MODE_DEMO, FunctionBuildConfig.isDemoMode) @@ -446,7 +409,6 @@ internal class SOPSettingView @JvmOverloads constructor( return@setOnCheckedChangeListener } hmiAction("SOP 雨天模式开关, ",isChecked) - Log.i(TAG,"SOP 雨天模式开关, $isChecked") FunctionBuildConfig.isRainMode = isChecked CallerAutoPilotControlManager.setRainMode(isChecked) CallerHmiViewControlListenerManager.invokeFuncMode(FUNC_MODE_RAIN, isChecked) @@ -463,7 +425,6 @@ internal class SOPSettingView @JvmOverloads constructor( FunctionBuildConfig.isWeakNetSlowDown = isChecked CallerAutoPilotControlManager.sendWeakNetSlowDown(isChecked) hmiAction("SOP 弱网减速停车, ",isChecked) - Log.i(TAG,"SOP 弱网减速停车, $isChecked") } //故障减速停车 @@ -472,7 +433,6 @@ internal class SOPSettingView @JvmOverloads constructor( FunctionBuildConfig.isFaultSlowDown = isChecked CallerAutoPilotControlManager.sendBreakdownSlowDown(isChecked) hmiAction("SOP 故障减速停车, ",isChecked) - Log.i(TAG,"SOP 故障减速停车, $isChecked") } //融合模式 rgFusionMode.setOnCheckedChangeListener { _, p1 -> @@ -499,7 +459,6 @@ internal class SOPSettingView @JvmOverloads constructor( } } hmiAction("SOP 融合模式, ",FunctionBuildConfig.fusionMode) - Log.i(TAG,"SOP 融合模式, ${FunctionBuildConfig.fusionMode}") CallerAutoPilotControlManager.sendFusionMode(FunctionBuildConfig.fusionMode) } } @@ -512,7 +471,6 @@ internal class SOPSettingView @JvmOverloads constructor( scTrafficLight.isChecked = !HmiBuildConfig.isShowTrafficLightView scTrafficLight.setOnCheckedChangeListener { _, isChecked -> hmiAction("SOP 红绿灯标识开关, ",isChecked) - Log.i(TAG,"SOP 红绿灯标识开关, $isChecked") if (isChecked) { CallerHmiManager.showTrafficLightView() } else { @@ -524,7 +482,6 @@ internal class SOPSettingView @JvmOverloads constructor( scSpeedLimit.isChecked = HmiBuildConfig.isShowLimitingVelocityView scSpeedLimit.setOnCheckedChangeListener { _, isChecked -> hmiAction("SOP 限速标识开关, ",isChecked) - Log.i(TAG,"SOP 限速标识开关, $isChecked") if (isChecked) { HmiBuildConfig.isShowLimitingVelocityView = true CallerHmiViewControlListenerManager.invokeVisible(IViewControlListener.LimitingVelocityView_TAG,View.VISIBLE) @@ -538,7 +495,6 @@ internal class SOPSettingView @JvmOverloads constructor( scIPCReport.isChecked = FunctionBuildConfig.isReportWarning scIPCReport.setOnCheckedChangeListener { _, isChecked -> hmiAction("SOP 是否开启异常上报, ",isChecked) - Log.i(TAG,"SOP 是否开启异常上报, $isChecked") FunctionBuildConfig.isReportWarning = isChecked } @@ -564,7 +520,6 @@ internal class SOPSettingView @JvmOverloads constructor( scShowBagRecordWindow.setOnCheckedChangeListener{_, isChecked -> FunctionBuildConfig.isShowBagRecordWindow = isChecked hmiAction("SOP 是否展示被动触发的录包弹窗, ",isChecked) - Log.i(TAG,"SOP 是否展示被动触发的录包弹窗, $isChecked") } //变道绕障的目标障碍物速度阈值 diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/utils/HmiActionLog.kt b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/utils/HmiActionLog.kt index c4c7d2450f..6e0d8be103 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/utils/HmiActionLog.kt +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/utils/HmiActionLog.kt @@ -1,6 +1,8 @@ package com.mogo.eagle.core.function.hmi.ui.utils import com.mogo.eagle.core.data.deva.chain.ChainConstant +import com.mogo.eagle.core.utilcode.mogo.logger.CallerLogger +import com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant.Companion.M_HMI import com.zhjt.service.chain.ChainLog class HmiActionLog { @@ -8,12 +10,13 @@ class HmiActionLog { companion object { @ChainLog( - linkChainLog = ChainConstant.CHAIN_TYPE_HMI, + linkChainLog = ChainConstant.CHAIN_TYPE_STATUS, linkCode = ChainConstant.CHAIN_SOURCE_HMI, nodeAliasCode = ChainConstant.CHAIN_CODE_HMI_ACTIONS, paramIndexes = [0, 1] ) fun hmiAction(data: Any, data1: Any) { + CallerLogger.d(M_HMI + data.toString(), data1) } } diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/vehicle/SteeringBrakeView.kt b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/vehicle/SteeringBrakeView.kt index f01abd657c..fff7dc45ea 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/vehicle/SteeringBrakeView.kt +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/vehicle/SteeringBrakeView.kt @@ -46,7 +46,7 @@ class SteeringBrakeView(context: Context, attrs: AttributeSet?) : ConstraintLayo } override fun onChassisLocationWGS84(gnssInfo: MogoLocation) { - //设置刹车信息,小于默认认为是刹车 //todo 优化sp获取,不要每次回调都去调用sp + //设置刹车信息,小于默认认为是刹车 //todo emArrow 优化sp获取,不要每次回调都去调用sp brakeLight = if (gnssInfo.acceleration < SharedPrefsMgr.getInstance(Utils.getApp()).getFloat( MoGoConfig.BRAKE_ACCELERATION_THRESHOLD, -2.5f @@ -61,7 +61,7 @@ class SteeringBrakeView(context: Context, attrs: AttributeSet?) : ConstraintLayo "---onAutopilotLightSwitchData ---Acceleration = " + gnssInfo.acceleration + "-- brakeLight = " + brakeLight ) ThreadUtils.runOnUiThread { - if (!isShowTurnLight) { //在不展示转向灯的情况下,展示车辆刹车的动效 + if (!isShowTurnLight) { //在不展示转向灯的情况下,展示车辆刹车的动效 todo emArrow 逻辑放入地图 brakeView.visibility = View.VISIBLE brakeView.setBrakeLight(brakeLight) } else { diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/vehicle/TakeOverView.kt b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/vehicle/TakeOverView.kt index a63be4c512..f8b7c2e69d 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/vehicle/TakeOverView.kt +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/vehicle/TakeOverView.kt @@ -3,7 +3,6 @@ package com.mogo.eagle.core.function.hmi.ui.vehicle import android.content.Context import android.os.CountDownTimer import android.util.AttributeSet -import android.util.Log import android.view.LayoutInflater import android.view.View import androidx.constraintlayout.widget.ConstraintLayout @@ -21,6 +20,8 @@ import com.mogo.eagle.core.function.call.hmi.CallerHmiManager import com.mogo.eagle.core.function.call.msgbox.CallerMsgBoxManager.saveMsgBox import com.mogo.eagle.core.function.hmi.R import com.mogo.eagle.core.utilcode.mogo.AppIdentityModeUtils +import com.mogo.eagle.core.utilcode.mogo.logger.CallerLogger +import com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant.Companion.M_HMI import com.mogo.eagle.core.utilcode.util.SoundPoolUtils import com.mogo.eagle.core.utilcode.util.ThreadUtils import com.zhjt.mogo.adas.data.bean.MogoReport @@ -55,13 +56,13 @@ class TakeOverView @JvmOverloads constructor( } override fun onAutopilotStatusResponse(state: Int) { - Log.i(TAG, "onAutopilotStatusResponse state=$state") + CallerLogger.i(M_HMI + TAG, "onAutopilotStatusResponse state=$state") if(state == 7){ isParallel = true - Log.i(TAG, "onAutopilotStatusResponse isParallel status=true") + CallerLogger.i(M_HMI + TAG, "onAutopilotStatusResponse isParallel status=true") }else if(state == 0 || state == 1){ isParallel = false - Log.i(TAG, "onAutopilotStatusResponse isParallel status=false") + CallerLogger.i(M_HMI + TAG, "onAutopilotStatusResponse isParallel status=false") } } @@ -119,10 +120,10 @@ class TakeOverView @JvmOverloads constructor( //弱网 MogoReport.Code.Error.EPARALLEL.AICLOUD_NETWORK_WEAK, MogoReport.Code.Error.EPARALLEL.AICLOUD_CONNECTION_ERROR -> { - Log.i(TAG, "收到弱网上报,当前自驾状态=$isParallel") + CallerLogger.i(M_HMI + TAG, "收到弱网上报,当前自驾状态=$isParallel") //如果是平行驾驶状态下,提示弱网接管 if(isParallel){ - Log.i(TAG,"是平行驾驶状态下,提示弱网接管") + CallerLogger.i(M_HMI + TAG,"是平行驾驶状态下,提示弱网接管") if(AppIdentityModeUtils.isM1(FunctionBuildConfig.appIdentityMode)){ //M1仅做提示音和消息盒子,无语音播报和提示接管动画 showM1ParallelDrivingWarning(EventTypeEnumNew.NETWORK_WEAK_EVENT.poiType, diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/RomaDistanceView.kt b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/RomaDistanceView.kt index 06166c9c46..9d882176ee 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/RomaDistanceView.kt +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/RomaDistanceView.kt @@ -6,7 +6,6 @@ import android.os.Looper import android.os.Message import android.text.Html import android.util.AttributeSet -import android.util.Log import android.util.TypedValue import android.view.LayoutInflater import android.view.View @@ -91,7 +90,6 @@ class RomaDistanceView @JvmOverloads constructor( override fun romaDistance(distance: String) { super.romaDistance(distance) dis = distance.toDouble().toInt() - Log.i(TAG, "romaDistance:$dis") } override fun onDetachedFromWindow() { diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/SpeedChartView.java b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/SpeedChartView.java index 47a53c4ce8..2f4a126c93 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/SpeedChartView.java +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/SpeedChartView.java @@ -22,13 +22,13 @@ import com.mogo.eagle.core.function.hmi.R; public class SpeedChartView extends View { //中心的文字描述 - private String mDes = "KM/H"; + private final String mDes = "KM/H"; //根据数据显示的圆弧Paint private Paint mArcPaint; //圆弧颜色 private int mArcColor; //圆弧的画笔的宽度 - private float mStrokeWith = getResources().getDimension(R.dimen.module_ext_arcView_stroke_with); + private final float mStrokeWith = getResources().getDimension(R.dimen.module_ext_arcView_stroke_with); //文字描述的paint private Paint mTextPaint; @@ -37,9 +37,9 @@ public class SpeedChartView extends View { //当前数据 private int currentValue; //最大数据 - private int maxValue = 240; + private final int maxValue = 240; //圆弧背景的开始和结束间的夹角大小 - private float mAngle = 270; + private final float mAngle = 270; //上次绘制圆弧夹角 private float lastAngle = 0; @@ -73,13 +73,13 @@ public class SpeedChartView extends View { mTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); //绘制中心的数值 mTextPaint.getTextBounds(mValue, 0, mValue.length(), mRect); - canvas.drawText(mValue, getWidth() / 2, getHeight() / 2 + mRect.height() / 2 - 10, mTextPaint); + canvas.drawText(mValue, getWidth() / 2.0f, getHeight() / 2.0f + mRect.height() / 2.0f - 10, mTextPaint); mTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); //绘制中心文字描述 mTextPaint.setTextSize(getResources().getDimension(R.dimen.module_ext_arcView_des_text_size)); mTextPaint.getTextBounds(mDes, 0, mDes.length(), mRect); - canvas.drawText(mDes, getWidth() / 2, getHeight() * 17 / 20 + mRect.height() / 2, mTextPaint); + canvas.drawText(mDes, getWidth() / 2.0f, getHeight() * 17.0f / 20.0f + mRect.height() / 2.0f, mTextPaint); } private void drawArc(Canvas canvas) { diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/SystemVersionView.kt b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/SystemVersionView.kt index a7a570fd39..c74b35b6a2 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/SystemVersionView.kt +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/hmi/ui/widget/SystemVersionView.kt @@ -365,7 +365,7 @@ class SystemVersionView @JvmOverloads constructor( * HQ、M1 MAP350开始弃用,其他车型MAP360开始弃用 */ override fun onAutopilotStatusRespByQuery(status: SystemStatusInfo.StatusInfo) { - Log.i(TAG, "hdMapVer=" + status.hdMapVer) + CallerLogger.i(M_HMI + TAG, "hdMapVer=" + status.hdMapVer) //hdMapVer返回示例:/home/mogo/autopilot/share/hadmap_engine/data/hadmap_data/db.sqlite|bj|2.2.7|对bus路线上的junction进行修改,对原609场景修改为6091、6092、6201、 6202四种细分场景,并对通往园区路口改为619 if (status.hdMapVer != null && status.hdMapVer.isNotEmpty()) { //对地图版本进行截取 @@ -384,7 +384,7 @@ class SystemVersionView @JvmOverloads constructor( * @param statusInf 数据 */ override fun onSystemStatus(statusInf: SsmInfo.SsmStatusInf) { - Log.i(TAG, "hdMapVer=" + statusInf.hdMapVer) + CallerLogger.i(M_HMI + TAG, "hdMapVer=" + statusInf.hdMapVer) //hdMapVer返回示例:/home/mogo/autopilot/share/hadmap_engine/data/hadmap_data/db.sqlite|bj|2.2.7|对bus路线上的junction进行修改,对原609场景修改为6091、6092、6201、 6202四种细分场景,并对通往园区路口改为619 if (statusInf.hdMapVer != null && statusInf.hdMapVer.isNotEmpty()) { //对地图版本进行截取 diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/MainActivity.kt b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/MainActivity.kt index e03ec1d562..781a780520 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/MainActivity.kt +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/MainActivity.kt @@ -31,7 +31,6 @@ import com.mogo.eagle.core.function.call.autopilot.CallerAutoPilotStatusListener import com.mogo.eagle.core.function.call.devatools.CallerDevaToolsManager import com.mogo.eagle.core.function.call.hmi.CallerHmiFloatViewManager import com.mogo.eagle.core.function.call.hmi.CallerHmiManager -import com.mogo.eagle.core.function.call.map.CallerMapUIServiceManager.getMapUIController import com.mogo.eagle.core.function.call.setting.CallerRequestActivityHandleManager import com.mogo.eagle.core.function.call.startup.CallerStartUpManager.initStageTwo import com.mogo.eagle.core.function.hmi.R @@ -358,7 +357,7 @@ open class MainActivity : MvpActivity(), MainView, } @ChainLog( - linkChainLog = ChainConstant.CHAIN_TYPE_INIT_STATUS, + linkChainLog = ChainConstant.CHAIN_TYPE_STATUS, linkCode = ChainConstant.CHAIN_SOURCE_INIT, nodeAliasCode = ChainConstant.CHAIN_CODE_REQUEST_PERMISSION, paramIndexes = [0, 1] diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/MainLauncherActivity.java b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/MainLauncherActivity.java index d051dd3928..a01eeb46aa 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/MainLauncherActivity.java +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/MainLauncherActivity.java @@ -2,7 +2,7 @@ package com.mogo.eagle.core.function.main; import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_CODE_START_UP; import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_SOURCE_INIT; -import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_TYPE_INIT_STATUS; +import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_TYPE_STATUS; import static com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant.M_HMI; import static com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant.M_MAIN; @@ -12,7 +12,6 @@ import android.os.Bundle; import android.os.Handler; import android.os.Process; import android.text.TextUtils; -import android.util.Log; import android.view.KeyEvent; import androidx.annotation.NonNull; @@ -150,7 +149,7 @@ public class MainLauncherActivity extends MainActivity implements IMogoIntentLis } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_INIT, nodeAliasCode = CHAIN_CODE_START_UP, paramIndexes = {0} @@ -205,7 +204,6 @@ public class MainLauncherActivity extends MainActivity implements IMogoIntentLis @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); - Log.d(TAG, " --- onConfigurationChanged --"); } @Override diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/PassengerLauncherActivity.java b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/PassengerLauncherActivity.java index 6a0586953c..41d252124d 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/PassengerLauncherActivity.java +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/PassengerLauncherActivity.java @@ -2,7 +2,7 @@ package com.mogo.eagle.core.function.main; import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_CODE_START_UP; import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_SOURCE_INIT; -import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_TYPE_INIT_STATUS; +import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_TYPE_STATUS; import static com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant.M_HMI; import android.bluetooth.BluetoothAdapter; @@ -13,7 +13,6 @@ import android.os.Bundle; import android.os.Handler; import android.os.Process; import android.text.TextUtils; -import android.util.Log; import androidx.annotation.Nullable; @@ -135,7 +134,7 @@ public class PassengerLauncherActivity extends MainActivity implements IMogoInte } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_INIT, nodeAliasCode = CHAIN_CODE_START_UP, paramIndexes = {0} @@ -199,7 +198,6 @@ public class PassengerLauncherActivity extends MainActivity implements IMogoInte Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null); isConnectedMethod.setAccessible(true); // boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null); - Log.d(TAG, "-- device.getName() = " + device.getName()); //device.getAddress() if (device.getName().equals("MINI_KEYBOARD")) { SharedPrefsMgr.getInstance(getContext()).putString("BLUETOOTH", device.getName()); } diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/VideoAdAtc.kt b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/VideoAdAtc.kt deleted file mode 100644 index cc73895c23..0000000000 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/VideoAdAtc.kt +++ /dev/null @@ -1,29 +0,0 @@ -package com.mogo.eagle.core.function.main - -import android.os.Bundle -import androidx.appcompat.app.AppCompatActivity -import com.mogo.eagle.core.function.hmi.R -import com.mogo.eagle.core.utilcode.util.BarUtils -import com.mogo.eagle.core.widget.TextureVideoView - -/** - * 视频广告 TODO 测试用的,可删除 - */ -class VideoAdAtc : AppCompatActivity() { - -// private lateinit var svpFrame: TextureVideoView -// -// override fun onCreate(savedInstanceState: Bundle?) { -// super.onCreate(savedInstanceState) -// setContentView(R.layout.activity_video_ad_atc) -// -// svpFrame = findViewById(R.id.svp_frame) -// -// val url = "android.resource://" + packageName + "/" + R.raw.mogo_ad -// svpFrame.videoPath = url -// svpFrame.start() -// -// BarUtils.hideStatusBarAndSticky(this.window) -// } - -} \ No newline at end of file diff --git a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/modules/MogoModulesManager.java b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/modules/MogoModulesManager.java index 0f53108175..208bfd8795 100644 --- a/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/modules/MogoModulesManager.java +++ b/core/function-impl/mogo-core-function-hmi/src/main/java/com/mogo/eagle/core/function/main/modules/MogoModulesManager.java @@ -150,40 +150,32 @@ public class MogoModulesManager implements MogoModulesHandler { @Override public void onDestroy() { - if (mModuleFunctionProviders != null) { - Collection modules = mModuleFunctionProviders.values(); - if (modules != null) { - for (IMoGoFunctionProvider module : modules) { - try { - CallerLogger.d(M_HMI + TAG, "destroy module: " + module.getFunctionName()); - module.onDestroy(); - } catch (Exception e) { - CallerLogger.e(M_HMI + TAG, e + " onDestroy"); - } + Collection fModules = mModuleFunctionProviders.values(); + if (!fModules.isEmpty()) { + for (IMoGoFunctionProvider module : fModules) { + try { + CallerLogger.d(M_HMI + TAG, "destroy module: " + module.getFunctionName()); + module.onDestroy(); + } catch (Exception e) { + CallerLogger.e(M_HMI + TAG, e + " onDestroy"); } } - mModuleNameFunctionProviders.clear(); } - if (mModuleFunctionProviders != null) { - mModuleFunctionProviders.clear(); - } - if (mModuleFunctionServerProviders != null) { - Collection modules = mModuleFunctionServerProviders.values(); - if (modules != null) { - for (IMoGoFunctionServerProvider module : modules) { - try { - CallerLogger.d(M_HMI + TAG, "destroy module: " + module.getFunctionName()); - module.onDestroy(); - } catch (Exception e) { - CallerLogger.e(M_HMI + TAG, e + " onDestroy"); - } + mModuleNameFunctionProviders.clear(); + mModuleFunctionProviders.clear(); + Collection fsModules = mModuleFunctionServerProviders.values(); + if (!fsModules.isEmpty()) { + for (IMoGoFunctionServerProvider module : fsModules) { + try { + CallerLogger.d(M_HMI + TAG, "destroy module: " + module.getFunctionName()); + module.onDestroy(); + } catch (Exception e) { + CallerLogger.e(M_HMI + TAG, e + " onDestroy"); } } - mModuleNameFunctionProviders.clear(); - } - if (mModuleFunctionServerProviders != null) { - mModuleFunctionServerProviders.clear(); } + mModuleNameFunctionProviders.clear(); + mModuleFunctionServerProviders.clear(); mActivity = null; } } diff --git a/core/function-impl/mogo-core-function-hmi/src/main/res/layout/activity_video_ad_atc.xml b/core/function-impl/mogo-core-function-hmi/src/main/res/layout/activity_video_ad_atc.xml deleted file mode 100644 index e23dfbdb4e..0000000000 --- a/core/function-impl/mogo-core-function-hmi/src/main/res/layout/activity_video_ad_atc.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - \ No newline at end of file diff --git a/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/identify/IdentifyFactory.kt b/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/identify/IdentifyFactory.kt index d9afd55947..e1f881e940 100644 --- a/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/identify/IdentifyFactory.kt +++ b/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/identify/IdentifyFactory.kt @@ -66,7 +66,7 @@ object IdentifyFactory : Identify, IMoGoObuStatusListener, IMoGoAutopilotCarConf } @ChainLog( - linkChainLog = ChainConstant.CHAIN_TYPE_INIT_STATUS, + linkChainLog = ChainConstant.CHAIN_TYPE_STATUS, linkCode = ChainConstant.CHAIN_SOURCE_INIT, nodeAliasCode = ChainConstant.CHAIN_CODE_ADAS_RECT_DATA, paramIndexes = [0] diff --git a/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/identify/TrackManager.java b/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/identify/TrackManager.java index 3c61109b02..f90860481e 100644 --- a/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/identify/TrackManager.java +++ b/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/identify/TrackManager.java @@ -120,10 +120,12 @@ public class TrackManager { trackObj = new TrackObj(data,s2CellId,s2LatLng); } } - mFilterTrafficData.put(uuid, trackObj.getCache()); - cellIdCaches.forcePut(uuid, trackObj.getCellIdPos()); - mMarkersCaches.put(uuid, trackObj); - trafficDataUuid.add(uuid); + if(trackObj != null){ + mFilterTrafficData.put(uuid, trackObj.getCache()); + cellIdCaches.forcePut(uuid, trackObj.getCellIdPos()); + mMarkersCaches.put(uuid, trackObj); + trafficDataUuid.add(uuid); + } //Log.i("costTime","" + (System.currentTimeMillis() - cost)); } return mFilterTrafficData; diff --git a/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/routeoverlay/RouteOverlayDrawer.java b/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/routeoverlay/RouteOverlayDrawer.java index 99f7e1f880..e0f1da6702 100644 --- a/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/routeoverlay/RouteOverlayDrawer.java +++ b/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/business/routeoverlay/RouteOverlayDrawer.java @@ -27,6 +27,7 @@ public class RouteOverlayDrawer { private Handler mRenderHandler; private final IMoGoOverlayManager mogoOverlayManager; private static volatile RouteOverlayDrawer sInstance; + private static final byte[] obj = new byte[0]; private Polyline.Options mPolylineOptions; private static final int COLOR_LIGHT = Color.parseColor("#BAEBF5"); @@ -55,7 +56,7 @@ public class RouteOverlayDrawer { public static RouteOverlayDrawer getInstance() { if (sInstance == null) { - synchronized (RouteOverlayDrawer.class) { + synchronized (obj) { if (sInstance == null) { sInstance = new RouteOverlayDrawer(); } diff --git a/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/smp/CarOverlay.java b/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/smp/CarOverlay.java index 5dfd37b6d0..277d473123 100644 --- a/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/smp/CarOverlay.java +++ b/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/smp/CarOverlay.java @@ -142,11 +142,7 @@ public class CarOverlay { if (directionMarker == null) { directionMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).setFlat(true).icon(fourCornersDescriptor).position(mLatLng)); - if (isDirectionVisible) { - directionMarker.setVisible(true); - } else { - directionMarker.setVisible(false); - } + directionMarker.setVisible(isDirectionVisible); } carMarker.setVisible(true); newAngle = bearing; @@ -269,7 +265,7 @@ public class CarOverlay { } try { IPoint p = carMarker.getGeoPoint(); - double newX = 0, newY = 0; + double newX, newY; if (currentFrameIndex++ < carMoveAnimationFrameNum) { newX = mapAnchorBackup.x + dXOffStep * currentFrameIndex; newY = mapAnchorBackup.y + dYOffStep * currentFrameIndex; diff --git a/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/smp/RoutePathConvertUtils.java b/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/utils/RoutePathConvertUtils.java similarity index 90% rename from core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/smp/RoutePathConvertUtils.java rename to core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/utils/RoutePathConvertUtils.java index b841bcbb56..2a663fbf1e 100644 --- a/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/smp/RoutePathConvertUtils.java +++ b/core/function-impl/mogo-core-function-map/src/main/java/com/mogo/eagle/core/function/utils/RoutePathConvertUtils.java @@ -1,4 +1,4 @@ -package com.mogo.eagle.core.function.smp; +package com.mogo.eagle.core.function.utils; import com.mogo.eagle.core.data.map.MogoLatLng; @@ -6,7 +6,6 @@ import java.util.List; public class RoutePathConvertUtils { - public List routeList; public int ROUTE_LEFT = 1; @@ -21,7 +20,7 @@ public class RoutePathConvertUtils { double v1x = latLng1.lat - latLng0.lat; double v1y = latLng1.lon - latLng0.lon; double v2x = latLng2.lat - latLng1.lat; - double v2y = latLng2.lon - latLng2.lon; + double v2y = latLng2.lon - latLng1.lon; double r = v1x* v2y - v1y*v2x; if (r > 0.0){ route_direction = ROUTE_LEFT; diff --git a/core/function-impl/mogo-core-function-patch/src/androidTest/java/com/mogo/launcer/patch/ExampleInstrumentedTest.kt b/core/function-impl/mogo-core-function-patch/src/androidTest/java/com/mogo/launcer/patch/ExampleInstrumentedTest.kt deleted file mode 100644 index 9390da3399..0000000000 --- a/core/function-impl/mogo-core-function-patch/src/androidTest/java/com/mogo/launcer/patch/ExampleInstrumentedTest.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.mogo.launcer.patch - -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.ext.junit.runners.AndroidJUnit4 - -import org.junit.Test -import org.junit.runner.RunWith - -import org.junit.Assert.* - -/** - * Instrumented test, which will execute on an Android device. - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -@RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { - @Test fun useAppContext() { // Context of the app under test. - val appContext = InstrumentationRegistry.getInstrumentation().targetContext - assertEquals("com.mogo.launcer.patch.test", appContext.packageName) - } -} \ No newline at end of file diff --git a/core/function-impl/mogo-core-function-patch/src/test/java/com/mogo/launcer/patch/ExampleUnitTest.kt b/core/function-impl/mogo-core-function-patch/src/test/java/com/mogo/launcer/patch/ExampleUnitTest.kt deleted file mode 100644 index bf47ec6404..0000000000 --- a/core/function-impl/mogo-core-function-patch/src/test/java/com/mogo/launcer/patch/ExampleUnitTest.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.mogo.launcer.patch - -import org.junit.Test - -import org.junit.Assert.* - -/** - * Example local unit test, which will execute on the development machine (host). - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -class ExampleUnitTest { - @Test fun addition_isCorrect() { - assertEquals(4, 2 + 2) - } -} \ No newline at end of file diff --git a/core/function-impl/mogo-core-function-startup/src/main/java/com/mogo/eagle/core/function/startup/stageone/HttpDnsStartUp.kt b/core/function-impl/mogo-core-function-startup/src/main/java/com/mogo/eagle/core/function/startup/stageone/HttpDnsStartUp.kt index 3a2f52121b..e3e8d81c80 100644 --- a/core/function-impl/mogo-core-function-startup/src/main/java/com/mogo/eagle/core/function/startup/stageone/HttpDnsStartUp.kt +++ b/core/function-impl/mogo-core-function-startup/src/main/java/com/mogo/eagle/core/function/startup/stageone/HttpDnsStartUp.kt @@ -27,7 +27,7 @@ import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_CODE_CL import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_CODE_CLOUD_RECONNECT import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_CODE_HTTP_DNS_ERROR_REASON import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_SOURCE_CLOUD -import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_INIT_STATUS +import com.mogo.eagle.core.data.deva.chain.ChainConstant.Companion.CHAIN_TYPE_STATUS import com.mogo.eagle.core.data.map.MogoLocation import com.mogo.eagle.core.function.api.autopilot.IMoGoChassisLocationGCJ02Listener import com.mogo.eagle.core.function.call.autopilot.CallerChassisLocationGCJ02ListenerManager @@ -193,7 +193,7 @@ class HttpDnsStartUp : AndroidStartup() { } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, nodeAliasCode = CHAIN_CODE_CLOUD_INIT, paramIndexes = [-1], @@ -205,7 +205,7 @@ class HttpDnsStartUp : AndroidStartup() { object : IMoGoTokenCallback { @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, parentNodeAliasCode = CHAIN_CODE_CLOUD_INIT, nodeAliasCode = CHAIN_CODE_CLOUD_PASSPORT_TOKEN, @@ -266,7 +266,7 @@ class HttpDnsStartUp : AndroidStartup() { IPassportSecret { @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, nodeAliasCode = CHAIN_CODE_CLOUD_PASSPORT_AUTH_OK, paramIndexes = [0] @@ -283,7 +283,7 @@ class HttpDnsStartUp : AndroidStartup() { } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, nodeAliasCode = CHAIN_CODE_CLOUD_PASSPORT_AUTH_FAILED, paramIndexes = [0, 1] @@ -362,7 +362,7 @@ class HttpDnsStartUp : AndroidStartup() { } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, nodeAliasCode = CHAIN_CODE_HTTP_DNS_ERROR_REASON, paramIndexes = [0] @@ -387,7 +387,7 @@ class HttpDnsStartUp : AndroidStartup() { } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, nodeAliasCode = CHAIN_CODE_CLOUD_RECONNECT, paramIndexes = [0, 1] diff --git a/core/mogo-core-data/src/main/java/com/mogo/eagle/core/data/deva/chain/ChainConstant.kt b/core/mogo-core-data/src/main/java/com/mogo/eagle/core/data/deva/chain/ChainConstant.kt index 670ce998aa..72c9cdd941 100644 --- a/core/mogo-core-data/src/main/java/com/mogo/eagle/core/data/deva/chain/ChainConstant.kt +++ b/core/mogo-core-data/src/main/java/com/mogo/eagle/core/data/deva/chain/ChainConstant.kt @@ -3,7 +3,7 @@ package com.mogo.eagle.core.data.deva.chain class ChainConstant { companion object{ - + //业务源 source // 与云平台数据链路交互 const val CHAIN_SOURCE_CLOUD = 0 // 与工控机相关交互 @@ -21,14 +21,14 @@ class ChainConstant { // OCH业务 const val CHAIN_SOURCE_OCH = 13 - const val CHAIN_TYPE_INIT_STATUS = 0 // 各个业务初始化信息,配置信息.链接状态 + //业务类型与下方文件名一一对应 + const val CHAIN_TYPE_STATUS = 0 // 各个业务初始化信息,配置信息.链接状态,点击信息 const val CHAIN_TYPE_GNSS = 1 // 工控定位数据 const val CHAIN_TYPE_SOCKET_AUTOPILOT = 2 // 包括自动驾驶状态,reportMsg,planning数据,全局路径数据 const val CHAIN_TYPE_SOCKET_DATA_TRACKED = 3 // 感知数据,现阶段记录云端漫游 const val CHAIN_TYPE_SOCKET_TRAJECTORY = 4 // 前车引导线,用于调试 const val CHAIN_TYPE_SOCKET_VEHICLE = 5 // 底盘数据 const val CHAIN_TYPE_SOCKET_TRAFFIC_LIGHT = 6 // 多元红绿灯聚合数据 - const val CHAIN_TYPE_HMI = 7 // 包括魔方和应用按钮点击 const val CHAIN_TYPE_V2X = 100 // V2X(V2I、V2N) const val CHAIN_TYPE_HD_MAP = 200 const val CHAIN_TYPE_ANR_LEAK = 300 @@ -43,7 +43,6 @@ class ChainConstant { const val CHAIN_LINK_LOG_ADAS_TRAJECTORY = "-adasTrajectory" const val CHAIN_LINK_LOG_ADAS_VEHICLE = "-adasVehicle" const val CHAIN_LINK_LOG_ADAS_TRAFFIC_LIGHT = "-UnionTrafficLight" - const val CHAIN_LINK_LOG_HMI_ACTIONS = "-eagleHMIActions" const val CHAIN_LINK_LOG_V2X = "-eagleCloudWSV2X" const val CHAIN_LINK_LOG_HD_MAP_BIZ = "-eagleHDMapBiz" const val CHAIN_LINK_LOG_RECORD_ANR = "-eagleRecordANR" @@ -83,9 +82,12 @@ class ChainConstant { const val CHAIN_CODE_INIT_ENV_RESTART = "CHAIN_CODE_INIT_ENV_RESTART" const val CHAIN_CODE_INIT_ON_MAP_LOADED = "CHAIN_CODE_INIT_ON_MAP_LOADED" const val CHAIN_CODE_INIT_ON_MAP_INIT = "CHAIN_CODE_INIT_ON_MAP_INIT" + const val CHAIN_CODE_BINDING_CAR = "CHAIN_CODE_BINDING_CAR" const val CHAIN_CODE_UPGRADE_APP = "CHAIN_CODE_UPGRADE_APP" const val CHAIN_CODE_MO_FANG_CONNECT = "CHAIN_CODE_MO_FANG_CONNECT" const val CHAIN_CODE_MAIN_BLOCK = "CHAIN_CODE_MAIN_BLOCK" + const val CHAIN_CODE_DISPATCH_RECEIVE = "CHAIN_CODE_DISPATCH_RECEIVE" + const val CHAIN_CODE_DISPATCH_START = "CHAIN_CODE_DISPATCH_START" const val CHAIN_CODE_CLOUD_INIT = "CHAIN_CODE_CLOUD_INIT" const val CHAIN_CODE_CLOUD_PASSPORT_TOKEN = "CHAIN_CODE_CLOUD_PASSPORT_TOKEN" diff --git a/core/mogo-core-data/src/main/java/com/mogo/eagle/core/data/enums/EventTypeEnumNew.kt b/core/mogo-core-data/src/main/java/com/mogo/eagle/core/data/enums/EventTypeEnumNew.kt index 4c993d936a..1b75421eb7 100644 --- a/core/mogo-core-data/src/main/java/com/mogo/eagle/core/data/enums/EventTypeEnumNew.kt +++ b/core/mogo-core-data/src/main/java/com/mogo/eagle/core/data/enums/EventTypeEnumNew.kt @@ -898,14 +898,6 @@ enum class EventTypeEnumNew( TYPE_ERROR_WEAKNESS.poiType ->{ TYPE_ERROR_WEAKNESS.poiTypeStr } - //学校 - TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiType ->{ - TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiTypeStr - } - //禁止停车 - TYPE_USECASE_ID_ROAD_NO_PARKING.poiType ->{ - TYPE_USECASE_ID_ROAD_NO_PARKING.poiTypeStr - } //超速行驶 TYPE_USECASE_ID_SLW.poiType ->{ TYPE_USECASE_ID_SLW.poiTypeStr @@ -918,10 +910,6 @@ enum class EventTypeEnumNew( TYPE_USECASE_ID_BREAKDOWN_WARNING.poiType ->{ TYPE_USECASE_ID_BREAKDOWN_WARNING.poiTypeStr } - //道路积水 - FOURS_PONDING.poiType ->{ - FOURS_PONDING.poiTypeStr - } //异常停车 TYPE_USECASE_ID_ROAD_PARKING.poiType ->{ TYPE_USECASE_ID_ROAD_PARKING.poiTypeStr @@ -1093,10 +1081,6 @@ enum class EventTypeEnumNew( FOURS_BLOCK_UP.poiType -> { R.drawable.icon_warning_v2x_congestion } - //积水 - FOURS_PONDING.poiType -> { - R.drawable.v2x_icon_jishui_vr - } //结冰 FOURS_ICE.poiType -> { R.drawable.v2x_icon_jiebing_vr @@ -1210,9 +1194,6 @@ enum class EventTypeEnumNew( TYPE_ERROR_WEAKNESS.poiType -> { R.drawable.icon_warning_v2x_abnormal_vehicle } - - TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiType -> TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiTypeSrcVr - TYPE_USECASE_ID_ROAD_NO_PARKING.poiType -> TYPE_USECASE_ID_ROAD_NO_PARKING.poiTypeSrcVr TYPE_USECASE_ID_SLW.poiType -> TYPE_USECASE_ID_SLW.poiTypeSrcVr TYPE_USECASE_ID_TJW.poiType -> TYPE_USECASE_ID_TJW.poiTypeSrcVr TYPE_USECASE_ID_BREAKDOWN_WARNING.poiType -> TYPE_USECASE_ID_BREAKDOWN_WARNING.poiTypeSrcVr @@ -1232,13 +1213,13 @@ enum class EventTypeEnumNew( TYPE_VEHICLE_QUEUE.poiType -> TYPE_VEHICLE_QUEUE.poiTypeSrcVr TYPE_NO_PASSING.poiType -> TYPE_NO_PASSING.poiTypeSrcVr TYPE_NO_TURNING_AROUND.poiType -> TYPE_NO_TURNING_AROUND.poiTypeSrcVr + TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiType -> TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiTypeSrcVr TYPE_USECASE_ID_ROAD_NO_PARKING.poiType -> TYPE_USECASE_ID_ROAD_NO_PARKING.poiTypeSrcVr TYPE_USECASE_ID_ROAD_NO_TOOTING.poiType -> TYPE_USECASE_ID_ROAD_NO_TOOTING.poiTypeSrcVr TYPE_USECASE_ID_ROAD_SPEED_LIMIT.poiType -> TYPE_USECASE_ID_ROAD_SPEED_LIMIT.poiTypeSrcVr TYPE_USECASE_ID_BUS_WARNING.poiType -> TYPE_USECASE_ID_BUS_WARNING.poiTypeSrcVr TYPE_USECASE_ID_NARROW_RIGHT.poiType -> TYPE_USECASE_ID_NARROW_RIGHT.poiTypeSrcVr TYPE_USECASE_ID_GAS_STATION.poiType -> TYPE_USECASE_ID_GAS_STATION.poiTypeSrcVr - TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiType -> TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiTypeSrcVr TYPE_USECASE_ID_ACCIDENT.poiType -> TYPE_USECASE_ID_ACCIDENT.poiTypeSrcVr TYPE_ATTENTION_CONFLUENCE.poiType -> TYPE_ATTENTION_CONFLUENCE.poiTypeSrcVr TYPE_PEDESTRIAN_CROSSING.poiType -> TYPE_PEDESTRIAN_CROSSING.poiTypeSrcVr @@ -1284,18 +1265,12 @@ enum class EventTypeEnumNew( TYPE_ERROR.poiType -> TYPE_ERROR.content TYPE_OPTIMAL_ROUTE_RECOMMEND.poiType -> TYPE_OPTIMAL_ROUTE_RECOMMEND.content GHOST_PROBE.poiType -> GHOST_PROBE.content - TYPE_USECASE_ID_IVP_RED.poiType -> TYPE_USECASE_ID_IVP_RED.content TYPE_USECASE_ID_IVP_GREEN.poiType -> TYPE_USECASE_ID_IVP_GREEN.content - TYPE_USECASE_ID_VRUCW_PERSON.poiType -> TYPE_USECASE_ID_VRUCW_PERSON.content TYPE_USECASE_ID_VRUCW_MOTOR_VEHICLES.poiType -> TYPE_USECASE_ID_VRUCW_MOTOR_VEHICLES.content TYPE_USECASE_ID_VRUCW_NOT_MOTOR_VEHICLES.poiType -> TYPE_USECASE_ID_VRUCW_NOT_MOTOR_VEHICLES.content TYPE_ERROR_WEAKNESS.poiType -> TYPE_ERROR_WEAKNESS.content - - TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiType -> TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.content - TYPE_USECASE_ID_ROAD_NO_PARKING.poiType -> TYPE_USECASE_ID_ROAD_NO_PARKING.content - TYPE_FOURS_ROAD_WORK.poiType -> TYPE_FOURS_ROAD_WORK.content TYPE_USECASE_ID_SLW.poiType -> TYPE_USECASE_ID_SLW.content TYPE_USECASE_ID_TJW.poiType -> TYPE_USECASE_ID_TJW.content TYPE_USECASE_ID_BREAKDOWN_WARNING.poiType -> TYPE_USECASE_ID_BREAKDOWN_WARNING.content @@ -1318,10 +1293,10 @@ enum class EventTypeEnumNew( TYPE_USECASE_ID_ROAD_NO_PARKING.poiType -> TYPE_USECASE_ID_ROAD_NO_PARKING.content TYPE_USECASE_ID_ROAD_NO_TOOTING.poiType -> TYPE_USECASE_ID_ROAD_NO_TOOTING.content TYPE_USECASE_ID_ROAD_SPEED_LIMIT.poiType -> TYPE_USECASE_ID_ROAD_SPEED_LIMIT.content + TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiType -> TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.content TYPE_USECASE_ID_BUS_WARNING.poiType -> TYPE_USECASE_ID_BUS_WARNING.content TYPE_USECASE_ID_NARROW_RIGHT.poiType -> TYPE_USECASE_ID_NARROW_RIGHT.content TYPE_USECASE_ID_GAS_STATION.poiType -> TYPE_USECASE_ID_GAS_STATION.content - TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiType -> TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.content TYPE_USECASE_ID_ACCIDENT.poiType -> TYPE_USECASE_ID_ACCIDENT.content TYPE_ATTENTION_CONFLUENCE.poiType -> TYPE_ATTENTION_CONFLUENCE.content TYPE_PEDESTRIAN_CROSSING.poiType -> TYPE_PEDESTRIAN_CROSSING.content @@ -1353,18 +1328,12 @@ enum class EventTypeEnumNew( TYPE_ERROR.poiType -> TYPE_ERROR.tts TYPE_OPTIMAL_ROUTE_RECOMMEND.poiType -> TYPE_OPTIMAL_ROUTE_RECOMMEND.tts GHOST_PROBE.poiType -> GHOST_PROBE.tts - TYPE_USECASE_ID_IVP_RED.poiType -> TYPE_USECASE_ID_IVP_RED.tts TYPE_USECASE_ID_IVP_GREEN.poiType -> TYPE_USECASE_ID_IVP_GREEN.tts - TYPE_USECASE_ID_VRUCW_PERSON.poiType -> TYPE_USECASE_ID_VRUCW_PERSON.tts TYPE_USECASE_ID_VRUCW_MOTOR_VEHICLES.poiType -> TYPE_USECASE_ID_VRUCW_MOTOR_VEHICLES.tts TYPE_USECASE_ID_VRUCW_NOT_MOTOR_VEHICLES.poiType -> TYPE_USECASE_ID_VRUCW_NOT_MOTOR_VEHICLES.tts TYPE_ERROR_WEAKNESS.poiType -> TYPE_ERROR_WEAKNESS.tts - - TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiType -> TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.tts - TYPE_USECASE_ID_ROAD_NO_PARKING.poiType -> TYPE_USECASE_ID_ROAD_NO_PARKING.tts - TYPE_FOURS_ROAD_WORK.poiType -> TYPE_FOURS_ROAD_WORK.tts TYPE_USECASE_ID_SLW.poiType -> TYPE_USECASE_ID_SLW.tts TYPE_USECASE_ID_TJW.poiType -> TYPE_USECASE_ID_TJW.tts TYPE_USECASE_ID_BREAKDOWN_WARNING.poiType -> TYPE_USECASE_ID_BREAKDOWN_WARNING.tts @@ -1387,10 +1356,10 @@ enum class EventTypeEnumNew( TYPE_USECASE_ID_ROAD_NO_PARKING.poiType -> TYPE_USECASE_ID_ROAD_NO_PARKING.tts TYPE_USECASE_ID_ROAD_NO_TOOTING.poiType -> TYPE_USECASE_ID_ROAD_NO_TOOTING.tts TYPE_USECASE_ID_ROAD_SPEED_LIMIT.poiType -> TYPE_USECASE_ID_ROAD_SPEED_LIMIT.tts + TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiType -> TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.tts TYPE_USECASE_ID_BUS_WARNING.poiType -> TYPE_USECASE_ID_BUS_WARNING.tts TYPE_USECASE_ID_NARROW_RIGHT.poiType -> TYPE_USECASE_ID_NARROW_RIGHT.tts TYPE_USECASE_ID_GAS_STATION.poiType -> TYPE_USECASE_ID_GAS_STATION.tts - TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.poiType -> TYPE_USECASE_ID_ROAD_PEDESTRIAN_SCHOOL.tts TYPE_USECASE_ID_ACCIDENT.poiType -> TYPE_USECASE_ID_ACCIDENT.tts TYPE_ATTENTION_CONFLUENCE.poiType -> TYPE_ATTENTION_CONFLUENCE.tts TYPE_PEDESTRIAN_CROSSING.poiType -> TYPE_PEDESTRIAN_CROSSING.tts diff --git a/core/mogo-core-function-call/src/main/java/com/mogo/eagle/core/function/call/autopilot/CallerParallelDrivingActionsListenerManager.kt b/core/mogo-core-function-call/src/main/java/com/mogo/eagle/core/function/call/autopilot/CallerParallelDrivingActionsListenerManager.kt index 1302ca1d20..7c39de1df7 100644 --- a/core/mogo-core-function-call/src/main/java/com/mogo/eagle/core/function/call/autopilot/CallerParallelDrivingActionsListenerManager.kt +++ b/core/mogo-core-function-call/src/main/java/com/mogo/eagle/core/function/call/autopilot/CallerParallelDrivingActionsListenerManager.kt @@ -1,6 +1,5 @@ package com.mogo.eagle.core.function.call.autopilot -import android.util.Log import com.mogo.eagle.core.function.api.autopilot.IMoGoParallelDrivingActionsListener import com.mogo.eagle.core.function.call.base.CallerBase @@ -44,10 +43,10 @@ object CallerParallelDrivingActionsListenerManager : } private fun notification() { - Log.i( - "xfk", - "是否可以启动平行驾驶=$isParallelDrivingAbility" - ) +// Log.i( +// "xfk", +// "是否可以启动平行驾驶=$isParallelDrivingAbility" +// ) M_LISTENERS.forEach { val listener = it.value listener.onParallelDrivingAbility( diff --git a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/AllAllowedHostnameVerifier.java b/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/AllAllowedHostnameVerifier.java deleted file mode 100644 index f0c9f355bb..0000000000 --- a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/AllAllowedHostnameVerifier.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.mogo.eagle.core.network; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSession; - -/** - * @author congtaowang - * @since 2019-08-30 - *

- * 信任所有域名 - */ -public class AllAllowedHostnameVerifier implements HostnameVerifier { - - @Override - public boolean verify( String hostname, SSLSession session ) { - return true; - } -} diff --git a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/NetConfig.java b/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/NetConfig.java index 4a6ea80e02..6242766dd6 100644 --- a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/NetConfig.java +++ b/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/NetConfig.java @@ -3,8 +3,6 @@ package com.mogo.eagle.core.network; import android.app.Application; import android.content.Context; -import com.mogo.cloud.passport.SpStorage; - import androidx.collection.ArraySet; import java.security.SecureRandom; @@ -13,7 +11,6 @@ import java.util.Set; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import okhttp3.Interceptor; @@ -34,15 +31,8 @@ public final class NetConfig { private final Set< Interceptor > interceptors = new ArraySet<>(); private final Set< Interceptor > networkInterceptors = new ArraySet<>(); - private final HostnameVerifier allowAllHostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify( String hostname, SSLSession session ) { - return true; - } - }; - private String signaturePrefix = "com.foundation.network"; - private HostnameVerifier hostnameVerifier = OkHostnameVerifier.INSTANCE; + private final HostnameVerifier hostnameVerifier = OkHostnameVerifier.INSTANCE; private Map< String, Object > publicParams; private boolean isLoggable; private Context appContext; diff --git a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/X509TrustManagerImpl.java b/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/X509TrustManagerImpl.java index 15e17ede03..a59abcf7dd 100644 --- a/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/X509TrustManagerImpl.java +++ b/core/mogo-core-network/src/main/java/com/mogo/eagle/core/network/X509TrustManagerImpl.java @@ -1,5 +1,7 @@ package com.mogo.eagle.core.network; +import android.annotation.SuppressLint; + import java.security.cert.CertificateException; import java.security.cert.X509Certificate; @@ -13,11 +15,13 @@ import javax.net.ssl.X509TrustManager; */ public class X509TrustManagerImpl implements X509TrustManager { + @SuppressLint("TrustAllX509TrustManager") @Override public void checkClientTrusted( X509Certificate[] chain, String authType ) throws CertificateException { } + @SuppressLint("TrustAllX509TrustManager") @Override public void checkServerTrusted( X509Certificate[] chain, String authType ) throws CertificateException { diff --git a/core/mogo-core-res/src/main/java/com/mogo/eagle/core/widget/TextureVideoView.java b/core/mogo-core-res/src/main/java/com/mogo/eagle/core/widget/TextureVideoView.java index 5dd31a933a..3669e249bb 100644 --- a/core/mogo-core-res/src/main/java/com/mogo/eagle/core/widget/TextureVideoView.java +++ b/core/mogo-core-res/src/main/java/com/mogo/eagle/core/widget/TextureVideoView.java @@ -43,7 +43,6 @@ import java.util.Map; * provides various display options such as scaling and tinting. */ public class TextureVideoView extends TextureView implements MediaPlayerControl { - private String TAG = "TextureVideoView"; public static final int STATE_ERROR = -1; public static final int STATE_IDLE = 0; diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/Platform.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/Platform.java index e0914b521b..bab8cb6c53 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/Platform.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/Platform.java @@ -154,6 +154,6 @@ final class Platform { * {@code x}, emulating the behavior of {@link BigDecimal#BigDecimal(double)}. */ static BigDecimal newBigDecimal(double x) { - return new BigDecimal(x); + return BigDecimal.valueOf(x); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/Real.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/Real.java index fe1fec67e9..db5e9ebc77 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/Real.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/Real.java @@ -284,18 +284,16 @@ strictfp class Real extends Number { /** Returns a BigDecimal representation of this extended precision real value. */ public BigDecimal bigValue() { - BigDecimal sum = new BigDecimal(values[0]); + BigDecimal sum = BigDecimal.valueOf(values[0]); for (int i = 1; i < values.length; i++) { - sum = sum.add(new BigDecimal(values[i])); + sum = sum.add(BigDecimal.valueOf(values[i])); } return sum.stripTrailingZeros(); } private static double[] copyOf(double[] array, int newLength) { double[] result = new double[newLength]; - for (int i = 0; i < newLength; i++) { - result[i] = array[i]; - } + System.arraycopy(array, 0, result, 0, newLength); return result; } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/S2FractalBuilder.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/S2FractalBuilder.java index 08ee285a38..375aed869f 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/S2FractalBuilder.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/S2FractalBuilder.java @@ -60,7 +60,7 @@ public class S2FractalBuilder { */ private double offsetFraction = 0; - private Random rand; + private final Random rand; /** You must call setMaxLevel() or setLevelForApproxMaxMedges() before calling makeLoop(). */ public S2FractalBuilder(Random rand) { @@ -124,7 +124,7 @@ public class S2FractalBuilder { /** Returns level from values in the range [1.5 * (4 ^ n), 6 * (4 ^ n)]. */ private static int levelFromEdges(int edges) { - return (int) Math.ceil(0.5 * Math.log(edges / 3) / Math.log(2)); + return (int) Math.ceil(0.5 * Math.log(edges / 3.0f) / Math.log(2)); } /** diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/S2Polygon.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/S2Polygon.java index 2da168e7ef..6b0f7aced4 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/S2Polygon.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/geometry/S2Polygon.java @@ -2571,7 +2571,6 @@ public final strictfp class S2Polygon implements S2Region, Comparable * interior is always on the left. */ public abstract class Shape implements S2Shape, Serializable { - // TODO measure this with benchmark. private static final int MAX_LINEAR_SEARCH_LOOPS = 5; // From benchmarks. private static final long serialVersionUID = 1L; diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideCircleBitmapTransform.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideCircleBitmapTransform.java index b56d33102a..31c073e9ba 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideCircleBitmapTransform.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideCircleBitmapTransform.java @@ -17,10 +17,10 @@ import java.security.MessageDigest; public class GlideCircleBitmapTransform extends BitmapTransformation { - private int mBorderWidth; - private int mBorderColor; - private String mKey; - private Context mContext; + private final int mBorderWidth; + private final int mBorderColor; + private final String mKey; + private final Context mContext; public GlideCircleBitmapTransform( Context context, String key, int borderWidth, int borderColor ) { this.mContext = context; @@ -38,9 +38,9 @@ public class GlideCircleBitmapTransform extends BitmapTransformation { int radius = newSize / 2; Bitmap bitmap = Bitmap.createBitmap( toTransform, x, y, newSize, newSize ); Bitmap result = pool.get( newSize, newSize, toTransform.getConfig() ); - if ( result == null ) { - result = Bitmap.createBitmap( newSize, newSize, toTransform.getConfig() ); - } +// if ( result == null ) { //get() func always return not null +// result = Bitmap.createBitmap( newSize, newSize, toTransform.getConfig() ); +// } Canvas canvas = new Canvas( result ); if ( mBorderWidth > 0 ) { @@ -49,12 +49,12 @@ public class GlideCircleBitmapTransform extends BitmapTransformation { borderPaint.setStrokeWidth( mBorderWidth ); borderPaint.setColor( mBorderColor ); borderPaint.setAntiAlias( true ); - canvas.drawCircle( radius, radius, radius - mBorderWidth / 2, borderPaint ); + canvas.drawCircle( radius, radius, radius - mBorderWidth / 2.0f, borderPaint ); } Paint paint = new Paint(); paint.setShader( new BitmapShader( bitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP ) ); paint.setAntiAlias( true ); - canvas.drawCircle( radius, radius, radius - mBorderWidth, paint ); + canvas.drawCircle( radius, radius, (float) (radius - mBorderWidth), paint ); DiskLruCacheManager.getInstance( mContext ).put( mKey, result ); diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundBitmapTransform.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundBitmapTransform.java index fe2a63f1d5..dd92f4b6a6 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundBitmapTransform.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundBitmapTransform.java @@ -18,11 +18,11 @@ import java.security.MessageDigest; public class GlideRoundBitmapTransform extends BitmapTransformation { - private int mRadius; - private int mBorderWidth; - private int mBorderColor; - private String mKey; - private Context mContext; + private final int mRadius; + private final int mBorderWidth; + private final int mBorderColor; + private final String mKey; + private final Context mContext; public GlideRoundBitmapTransform( Context context, String key, int radius, int borderWidth, int borderColor ) { this.mContext = context; @@ -39,11 +39,11 @@ public class GlideRoundBitmapTransform extends BitmapTransformation { } int width = toTransform.getWidth(); int height = toTransform.getHeight(); - RectF rectF = new RectF( mBorderWidth, mBorderWidth, width - mBorderWidth, height - mBorderWidth ); + RectF rectF = new RectF( mBorderWidth, mBorderWidth, (float) (width - mBorderWidth), (float) (height - mBorderWidth) ); Bitmap result = pool.get( width, height, toTransform.getConfig() ); - if ( result == null ) { - result = toTransform.copy( toTransform.getConfig(), true ); - } +// if ( result == null ) { //get() func always return not null +// result = toTransform.copy( toTransform.getConfig(), true ); +// } Canvas canvas = new Canvas( result ); Paint paint = new Paint(); paint.setShader( new BitmapShader( toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP ) ); diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundedCornersTransform.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundedCornersTransform.java index a16f333132..c1cee04393 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundedCornersTransform.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/transform/GlideRoundedCornersTransform.java @@ -22,8 +22,8 @@ import androidx.annotation.NonNull; * @author tongchenfei */ public class GlideRoundedCornersTransform extends CenterCrop { - private float mRadius; - private CornerType mCornerType; + private final float mRadius; + private final CornerType mCornerType; private static final int VERSION = 1; private static final String ID = BuildConfig.LIBRARY_PACKAGE_NAME + "GlideRoundedCornersTransform." + VERSION; private static final byte[] ID_BYTES = ID.getBytes(CHARSET); @@ -62,10 +62,10 @@ public class GlideRoundedCornersTransform extends CenterCrop { int height = source.getHeight(); Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); - if (result == null) { - result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config - .ARGB_8888); - } +// if (result == null) { //get() func always return not null +// result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config +// .ARGB_8888); +// } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader @@ -102,6 +102,7 @@ public class GlideRoundedCornersTransform extends CenterCrop { drawPath(rids, canvas, paint, path, width, height); break; case TOP: + case TOP_LEFT_TOP_RIGHT: rids = new float[]{mRadius, mRadius, mRadius, mRadius, 0.0f, 0.0f, 0.0f, 0.0f}; drawPath(rids, canvas, paint, path, width, height); break; @@ -133,10 +134,6 @@ public class GlideRoundedCornersTransform extends CenterCrop { rids = new float[]{0.0f, 0.0f, mRadius, mRadius, mRadius, mRadius, mRadius, mRadius}; drawPath(rids, canvas, paint, path, width, height); break; - case TOP_LEFT_TOP_RIGHT: - rids = new float[]{mRadius, mRadius, mRadius, mRadius, 0.0f, 0.0f, 0.0f, 0.0f}; - drawPath(rids, canvas, paint, path, width, height); - break; default: throw new RuntimeException("RoundedCorners type not belong to CornerType"); } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCache.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCache.java index 0d7b30611a..25e5e0a8c8 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCache.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCache.java @@ -143,13 +143,13 @@ final class DiskLruCache implements Closeable { private final File journalFileBackup; private final int appVersion; private long maxSize; - private int maxFileCount; + private final int maxFileCount; private final int valueCount; private long size = 0; private int fileCount = 0; private Writer journalWriter; private final LinkedHashMap lruEntries = - new LinkedHashMap(0, 0.75f, true); + new LinkedHashMap<>(0, 0.75f, true); private int redundantOpCount; /** @@ -161,7 +161,7 @@ final class DiskLruCache implements Closeable { /** This cache uses a single background thread to evict entries. */ final ThreadPoolExecutor executorService = - new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue()); + new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); private final Callable cleanupCallable = new Callable() { public Void call() throws Exception { synchronized (DiskLruCache.this) { @@ -355,9 +355,8 @@ final class DiskLruCache implements Closeable { journalWriter.close(); } - Writer writer = new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII)); - try { + try (Writer writer = new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII))) { writer.write(MAGIC); writer.write("\n"); writer.write(VERSION_1); @@ -375,8 +374,6 @@ final class DiskLruCache implements Closeable { writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); } } - } finally { - writer.close(); } if (journalFile.exists()) { @@ -446,7 +443,7 @@ final class DiskLruCache implements Closeable { } redundantOpCount++; - journalWriter.append(READ + ' ' + key + '\n'); + journalWriter.append(READ + ' ').append(key).append(String.valueOf('\n')); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } @@ -622,7 +619,7 @@ final class DiskLruCache implements Closeable { } redundantOpCount++; - journalWriter.append(REMOVE + ' ' + key + '\n'); + journalWriter.append(REMOVE + ' ').append(key).append(String.valueOf('\n')); lruEntries.remove(key); if (journalRebuildRequired()) { @@ -656,7 +653,7 @@ final class DiskLruCache implements Closeable { if (journalWriter == null) { return; // Already closed. } - for (Entry entry : new ArrayList(lruEntries.values())) { + for (Entry entry : new ArrayList<>(lruEntries.values())) { if (entry.currentEditor != null) { entry.currentEditor.abort(); } @@ -706,7 +703,7 @@ final class DiskLruCache implements Closeable { public final class Snapshot implements Closeable { private final String key; private final long sequenceNumber; - private File[] files; + private final File[] files; private final InputStream[] ins; private final long[] lengths; @@ -756,7 +753,7 @@ final class DiskLruCache implements Closeable { private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() { @Override - public void write(int b) throws IOException { + public void write(int b) { // Eat all writes silently. Nom nom. } }; @@ -777,7 +774,7 @@ final class DiskLruCache implements Closeable { * Returns an unbuffered input stream to read the last committed value, * or null if no value has been committed. */ - public InputStream newInputStream(int index) throws IOException { + public InputStream newInputStream(int index) { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); @@ -809,7 +806,7 @@ final class DiskLruCache implements Closeable { * {@link #commit} is called. The returned output stream does not throw * IOExceptions. */ - public OutputStream newOutputStream(int index) throws IOException { + public OutputStream newOutputStream(int index) { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); @@ -936,7 +933,7 @@ final class DiskLruCache implements Closeable { this.lengths = new long[valueCount]; } - public String getLengths() throws IOException { + public String getLengths() { StringBuilder result = new StringBuilder(); for (long size : lengths) { result.append(' ').append(size); diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCacheManager.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCacheManager.java index 5742564602..ead1ad4ea4 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCacheManager.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCacheManager.java @@ -22,12 +22,12 @@ import java.security.MessageDigest; public class DiskLruCacheManager { private DiskLruCache diskLruCache; - private static DiskLruCacheManager instance; - - private final int MAX_CACHE_SIZE = 64 * 1024 * 1024; + private static volatile DiskLruCacheManager instance; + private static final byte[] obj = new byte[0]; private DiskLruCacheManager(Context context) { try { + int MAX_CACHE_SIZE = 64 * 1024 * 1024; diskLruCache = DiskLruCache.open(context.getCacheDir(), 1, 1, MAX_CACHE_SIZE, Integer.MAX_VALUE); } catch (Exception e) { @@ -37,7 +37,7 @@ public class DiskLruCacheManager { public static DiskLruCacheManager getInstance(Context context) { if (instance == null) { - synchronized (DiskLruCacheManager.class) { + synchronized (obj) { if (instance == null) { instance = new DiskLruCacheManager(context.getApplicationContext()); } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java index e67902356f..1379120eda 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java @@ -107,6 +107,8 @@ final class LoggerPrinter implements Printer { } } + private static final String xmlHtml = "{http://xml.apache.org/xslt}indent-amount"; + public void xml( String tag, String xml) { if ( TextUtils.isEmpty(xml)) { this.d(tag, "Empty/Null xml content"); @@ -116,7 +118,7 @@ final class LoggerPrinter implements Printer { StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("indent", "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + transformer.setOutputProperty(xmlHtml, "2"); transformer.transform(e, xmlOutput); this.d(tag, xmlOutput.getWriter().toString().replaceFirst(">", ">\n")); } catch ( TransformerException var5) { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ActivityUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ActivityUtils.java index 79f51e2dc9..a50b114c09 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ActivityUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ActivityUtils.java @@ -133,7 +133,7 @@ public final class ActivityUtils { @Nullable private static Activity getActivityFromDecorContext(@Nullable Context context) { if (context == null) return null; - if (context.getClass().getName().equals("com.android.internal.policy.DecorContext")) { + if ("com.android.internal.policy.DecorContext".equals(context.getClass().getName())) { try { Field mActivityContextField = context.getClass().getDeclaredField("mActivityContext"); mActivityContextField.setAccessible(true); diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ArrayUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ArrayUtils.java deleted file mode 100644 index 8949cd34a9..0000000000 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ArrayUtils.java +++ /dev/null @@ -1,2143 +0,0 @@ -package com.mogo.eagle.core.utilcode.util; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -/** - *

- *     author: blankj
- *     blog  : http://blankj.com
- *     time  : 2019/08/10
- *     desc  : utils about array
- * 
- */ -public class ArrayUtils { - - public static final int INDEX_NOT_FOUND = -1; - - private ArrayUtils() { - throw new UnsupportedOperationException("u can't instantiate me..."); - } - - /** - * Returns a new array only of those given elements. - * - * @param array The array. - * @return a new array only of those given elements. - */ - @NonNull - public static T[] newArray(T... array) { - return array; - } - - @NonNull - public static long[] newLongArray(long... array) { - return array; - } - - @NonNull - public static int[] newIntArray(int... array) { - return array; - } - - @NonNull - public static short[] newShortArray(short... array) { - return array; - } - - @NonNull - public static char[] newCharArray(char... array) { - return array; - } - - @NonNull - public static byte[] newByteArray(byte... array) { - return array; - } - - @NonNull - public static double[] newDoubleArray(double... array) { - return array; - } - - @NonNull - public static float[] newFloatArray(float... array) { - return array; - } - - @NonNull - public static boolean[] newBooleanArray(boolean... array) { - return array; - } - - /** - * Return the array is empty. - * - * @param array The array. - * @return {@code true}: yes
{@code false}: no - */ - public static boolean isEmpty(@Nullable Object array) { - return getLength(array) == 0; - } - - /** - * Return the size of array. - * - * @param array The array. - * @return the size of array - */ - public static int getLength(@Nullable Object array) { - if (array == null) return 0; - return Array.getLength(array); - } - - public static boolean isSameLength(@Nullable Object array1, @Nullable Object array2) { - return getLength(array1) == getLength(array2); - } - - /** - * Get the value of the specified index of the array. - * - * @param array The array. - * @param index The index into the array. - * @return the value of the specified index of the array - */ - @Nullable - public static Object get(@Nullable Object array, int index) { - return get(array, index, null); - } - - /** - * Get the value of the specified index of the array. - * - * @param array The array. - * @param index The index into the array. - * @param defaultValue The default value. - * @return the value of the specified index of the array - */ - @Nullable - public static Object get(@Nullable Object array, int index, @Nullable Object defaultValue) { - if (array == null) return defaultValue; - try { - return Array.get(array, index); - } catch (Exception ignore) { - return defaultValue; - } - } - - /** - * Set the value of the specified index of the array. - * - * @param array The array. - * @param index The index into the array. - * @param value The new value of the indexed component. - */ - public static void set(@Nullable Object array, int index, @Nullable Object value) { - if (array == null) return; - Array.set(array, index, value); - } - - /** - * Return whether the two arrays are equals. - * - * @param a One array. - * @param a2 The other array. - * @return {@code true}: yes
{@code false}: no - */ - public static boolean equals(@Nullable Object[] a, @Nullable Object[] a2) { - return Arrays.deepEquals(a, a2); - } - - public static boolean equals(boolean[] a, boolean[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(byte[] a, byte[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(char[] a, char[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(double[] a, double[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(float[] a, float[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(int[] a, int[] a2) { - return Arrays.equals(a, a2); - } - - public static boolean equals(short[] a, short[] a2) { - return Arrays.equals(a, a2); - } - - /////////////////////////////////////////////////////////////////////////// - // reverse - /////////////////////////////////////////////////////////////////////////// - - /** - *

Reverses the order of the given array.

- * - *

There is no special handling for multi-dimensional arrays.

- * - *

This method does nothing for a null input array.

- * - * @param array the array to reverse, may be null - */ - public static void reverse(T[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - T tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(long[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - long tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(int[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - int tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(short[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - short tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(char[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - char tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(byte[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - byte tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(double[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - double tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(float[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - float tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - public static void reverse(boolean[] array) { - if (array == null) { - return; - } - int i = 0; - int j = array.length - 1; - boolean tmp; - while (j > i) { - tmp = array[j]; - array[j] = array[i]; - array[i] = tmp; - j--; - i++; - } - } - - /////////////////////////////////////////////////////////////////////////// - // copy - /////////////////////////////////////////////////////////////////////////// - - /** - *

Copies the specified array and handling - * null.

- * - *

The objects in the array are not cloned, thus there is no special - * handling for multi-dimensional arrays.

- * - *

This method returns null for a null input array.

- * - * @param array the array to shallow clone, may be null - * @return the cloned array, null if null input - */ - @Nullable - public static T[] copy(@Nullable T[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static long[] copy(@Nullable long[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static int[] copy(@Nullable int[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static short[] copy(@Nullable short[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static char[] copy(@Nullable char[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static byte[] copy(@Nullable byte[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static double[] copy(@Nullable double[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static float[] copy(@Nullable float[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - public static boolean[] copy(@Nullable boolean[] array) { - if (array == null) return null; - return subArray(array, 0, array.length); - } - - @Nullable - private static Object realCopy(@Nullable Object array) { - if (array == null) return null; - return realSubArray(array, 0, getLength(array)); - } - - /////////////////////////////////////////////////////////////////////////// - // subArray - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static T[] subArray(@Nullable T[] array, int startIndexInclusive, int endIndexExclusive) { - //noinspection unchecked - return (T[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static long[] subArray(@Nullable long[] array, int startIndexInclusive, int endIndexExclusive) { - return (long[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static int[] subArray(@Nullable int[] array, int startIndexInclusive, int endIndexExclusive) { - return (int[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static short[] subArray(@Nullable short[] array, int startIndexInclusive, int endIndexExclusive) { - return (short[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static char[] subArray(@Nullable char[] array, int startIndexInclusive, int endIndexExclusive) { - return (char[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static byte[] subArray(@Nullable byte[] array, int startIndexInclusive, int endIndexExclusive) { - return (byte[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static double[] subArray(@Nullable double[] array, int startIndexInclusive, int endIndexExclusive) { - return (double[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static float[] subArray(@Nullable float[] array, int startIndexInclusive, int endIndexExclusive) { - return (float[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - public static boolean[] subArray(@Nullable boolean[] array, int startIndexInclusive, int endIndexExclusive) { - return (boolean[]) realSubArray(array, startIndexInclusive, endIndexExclusive); - } - - @Nullable - private static Object realSubArray(@Nullable Object array, int startIndexInclusive, int endIndexExclusive) { - if (array == null) { - return null; - } - if (startIndexInclusive < 0) { - startIndexInclusive = 0; - } - int length = getLength(array); - if (endIndexExclusive > length) { - endIndexExclusive = length; - } - int newSize = endIndexExclusive - startIndexInclusive; - Class type = array.getClass().getComponentType(); - if (newSize <= 0) { - return Array.newInstance(type, 0); - } - Object subArray = Array.newInstance(type, newSize); - System.arraycopy(array, startIndexInclusive, subArray, 0, newSize); - return subArray; - } - - /////////////////////////////////////////////////////////////////////////// - // add - /////////////////////////////////////////////////////////////////////////// - - /** - *

Copies the given array and adds the given element at the end of the new array.

- * - *

The new array contains the same elements of the input - * array plus the given element in the last position. The component type of - * the new array is the same as that of the input array.

- * - *

If the input array is null, a new one element array is returned - * whose component type is the same as the element.

- * - *
-     * ArrayUtils.realAdd(null, null)      = [null]
-     * ArrayUtils.realAdd(null, "a")       = ["a"]
-     * ArrayUtils.realAdd(["a"], null)     = ["a", null]
-     * ArrayUtils.realAdd(["a"], "b")      = ["a", "b"]
-     * ArrayUtils.realAdd(["a", "b"], "c") = ["a", "b", "c"]
-     * 
- * - * @param array the array to "realAdd" the element to, may be null - * @param element the object to realAdd - * @return A new array containing the existing elements plus the new element - */ - @NonNull - public static T[] add(@Nullable T[] array, @Nullable T element) { - Class type = array != null ? array.getClass() : (element != null ? element.getClass() : Object.class); - return (T[]) realAddOne(array, element, type); - } - - @NonNull - public static boolean[] add(@Nullable boolean[] array, boolean element) { - return (boolean[]) realAddOne(array, element, Boolean.TYPE); - } - - @NonNull - public static byte[] add(@Nullable byte[] array, byte element) { - return (byte[]) realAddOne(array, element, Byte.TYPE); - } - - @NonNull - public static char[] add(@Nullable char[] array, char element) { - return (char[]) realAddOne(array, element, Character.TYPE); - } - - @NonNull - public static double[] add(@Nullable double[] array, double element) { - return (double[]) realAddOne(array, element, Double.TYPE); - } - - @NonNull - public static float[] add(@Nullable float[] array, float element) { - return (float[]) realAddOne(array, element, Float.TYPE); - } - - @NonNull - public static int[] add(@Nullable int[] array, int element) { - return (int[]) realAddOne(array, element, Integer.TYPE); - } - - @NonNull - public static long[] add(@Nullable long[] array, long element) { - return (long[]) realAddOne(array, element, Long.TYPE); - } - - @NonNull - public static short[] add(@Nullable short[] array, short element) { - return (short[]) realAddOne(array, element, Short.TYPE); - } - - @NonNull - private static Object realAddOne(@Nullable Object array, @Nullable Object element, Class newArrayComponentType) { - Object newArray; - int arrayLength = 0; - if (array != null) { - arrayLength = getLength(array); - newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1); - System.arraycopy(array, 0, newArray, 0, arrayLength); - } else { - newArray = Array.newInstance(newArrayComponentType, 1); - } - Array.set(newArray, arrayLength, element); - return newArray; - } - - /** - *

Adds all the elements of the given arrays into a new array.

- *

The new array contains all of the element of array1 followed - * by all of the elements array2. When an array is returned, it is always - * a new array.

- * - *
-     * ArrayUtils.add(null, null)     = null
-     * ArrayUtils.add(array1, null)   = copy of array1
-     * ArrayUtils.add(null, array2)   = copy of array2
-     * ArrayUtils.add([], [])         = []
-     * ArrayUtils.add([null], [null]) = [null, null]
-     * ArrayUtils.add(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
-     * 
- * - * @param array1 the first array whose elements are added to the new array, may be null - * @param array2 the second array whose elements are added to the new array, may be null - * @return The new array, null if null array inputs. - * The type of the new array is the type of the first array. - */ - @Nullable - public static T[] add(@Nullable T[] array1, @Nullable T[] array2) { - return (T[]) realAddArr(array1, array2); - } - - @Nullable - public static boolean[] add(@Nullable boolean[] array1, @Nullable boolean[] array2) { - return (boolean[]) realAddArr(array1, array2); - } - - @Nullable - public static char[] add(@Nullable char[] array1, @Nullable char[] array2) { - return (char[]) realAddArr(array1, array2); - } - - @Nullable - public static byte[] add(@Nullable byte[] array1, @Nullable byte[] array2) { - return (byte[]) realAddArr(array1, array2); - } - - @Nullable - public static short[] add(@Nullable short[] array1, @Nullable short[] array2) { - return (short[]) realAddArr(array1, array2); - } - - @Nullable - public static int[] add(@Nullable int[] array1, @Nullable int[] array2) { - return (int[]) realAddArr(array1, array2); - } - - @Nullable - public static long[] add(@Nullable long[] array1, @Nullable long[] array2) { - return (long[]) realAddArr(array1, array2); - } - - @Nullable - public static float[] add(@Nullable float[] array1, @Nullable float[] array2) { - return (float[]) realAddArr(array1, array2); - } - - @Nullable - public static double[] add(@Nullable double[] array1, @Nullable double[] array2) { - return (double[]) realAddArr(array1, array2); - } - - private static Object realAddArr(@Nullable Object array1, @Nullable Object array2) { - if (array1 == null && array2 == null) return null; - if (array1 == null) { - return realCopy(array2); - } - if (array2 == null) { - return realCopy(array1); - } - int len1 = getLength(array1); - int len2 = getLength(array2); - Object joinedArray = Array.newInstance(array1.getClass().getComponentType(), len1 + len2); - System.arraycopy(array1, 0, joinedArray, 0, len1); - System.arraycopy(array2, 0, joinedArray, len1, len2); - return joinedArray; - } - - /** - *

Inserts the specified element at the specified position in the array. - * Shifts the element currently at that position (if any) and any subsequent - * elements to the right (adds one to their indices).

- * - *

This method returns a new array with the same elements of the input - * array plus the given element on the specified position. The component - * type of the returned array is always the same as that of the input - * array.

- * - *

If the input array is null, a new one element array is returned - * whose component type is the same as the element.

- * - *
-     * ArrayUtils.add(null, 0, null)        = null
-     * ArrayUtils.add(null, 0, ["a"])       = ["a"]
-     * ArrayUtils.add(["a"], 1, null)       = ["a"]
-     * ArrayUtils.add(["a"], 1, ["b"])      = ["a", "b"]
-     * ArrayUtils.add(["a", "b"], 2, ["c"]) = ["a", "b", "c"]
-     * 
- * - * @param array1 the array to realAdd the element to, may be null - * @param index the position of the new object - * @param array2 the array to realAdd - * @return A new array containing the existing elements and the new element - * @throws IndexOutOfBoundsException if the index is out of range - * (index < 0 || index > array.length). - */ - @Nullable - public static T[] add(@Nullable T[] array1, int index, @Nullable T[] array2) { - Class clss; - if (array1 != null) { - clss = array1.getClass().getComponentType(); - } else if (array2 != null) { - clss = array2.getClass().getComponentType(); - } else { - return null; - } - return (T[]) realAddArr(array1, index, array2, clss); - } - - @Nullable - public static boolean[] add(@Nullable boolean[] array1, int index, @Nullable boolean[] array2) { - Object result = realAddArr(array1, index, array2, Boolean.TYPE); - if (result == null) return null; - return (boolean[]) result; - } - - public static char[] add(@Nullable char[] array1, int index, @Nullable char[] array2) { - Object result = realAddArr(array1, index, array2, Character.TYPE); - if (result == null) return null; - return (char[]) result; - } - - @Nullable - public static byte[] add(@Nullable byte[] array1, int index, @Nullable byte[] array2) { - Object result = realAddArr(array1, index, array2, Byte.TYPE); - if (result == null) return null; - return (byte[]) result; - } - - @Nullable - public static short[] add(@Nullable short[] array1, int index, @Nullable short[] array2) { - Object result = realAddArr(array1, index, array2, Short.TYPE); - if (result == null) return null; - return (short[]) result; - } - - @Nullable - public static int[] add(@Nullable int[] array1, int index, @Nullable int[] array2) { - Object result = realAddArr(array1, index, array2, Integer.TYPE); - if (result == null) return null; - return (int[]) result; - } - - @Nullable - public static long[] add(@Nullable long[] array1, int index, @Nullable long[] array2) { - Object result = realAddArr(array1, index, array2, Long.TYPE); - if (result == null) return null; - return (long[]) result; - } - - @Nullable - public static float[] add(@Nullable float[] array1, int index, @Nullable float[] array2) { - Object result = realAddArr(array1, index, array2, Float.TYPE); - if (result == null) return null; - return (float[]) result; - } - - @Nullable - public static double[] add(@Nullable double[] array1, int index, @Nullable double[] array2) { - Object result = realAddArr(array1, index, array2, Double.TYPE); - if (result == null) return null; - return (double[]) result; - } - - @Nullable - private static Object realAddArr(@Nullable Object array1, int index, @Nullable Object array2, Class clss) { - if (array1 == null && array2 == null) return null; - int len1 = getLength(array1); - int len2 = getLength(array2); - if (len1 == 0) { - if (index != 0) { - throw new IndexOutOfBoundsException("Index: " + index + ", array1 Length: 0"); - } - return realCopy(array2); - } - if (len2 == 0) { - return realCopy(array1); - } - if (index > len1 || index < 0) { - throw new IndexOutOfBoundsException("Index: " + index + ", array1 Length: " + len1); - } - Object joinedArray = Array.newInstance(array1.getClass().getComponentType(), len1 + len2); - if (index == len1) { - System.arraycopy(array1, 0, joinedArray, 0, len1); - System.arraycopy(array2, 0, joinedArray, len1, len2); - } else if (index == 0) { - System.arraycopy(array2, 0, joinedArray, 0, len2); - System.arraycopy(array1, 0, joinedArray, len2, len1); - } else { - System.arraycopy(array1, 0, joinedArray, 0, index); - System.arraycopy(array2, 0, joinedArray, index, len2); - System.arraycopy(array1, index, joinedArray, index + len2, len1 - index); - } - return joinedArray; - } - - /** - *

Inserts the specified element at the specified position in the array. - * Shifts the element currently at that position (if any) and any subsequent - * elements to the right (adds one to their indices).

- * - *

This method returns a new array with the same elements of the input - * array plus the given element on the specified position. The component - * type of the returned array is always the same as that of the input - * array.

- * - *

If the input array is null, a new one element array is returned - * whose component type is the same as the element.

- * - *
-     * ArrayUtils.add(null, 0, null)      = [null]
-     * ArrayUtils.add(null, 0, "a")       = ["a"]
-     * ArrayUtils.add(["a"], 1, null)     = ["a", null]
-     * ArrayUtils.add(["a"], 1, "b")      = ["a", "b"]
-     * ArrayUtils.add(["a", "b"], 3, "c") = ["a", "b", "c"]
-     * 
- * - * @param array the array to realAdd the element to, may be null - * @param index the position of the new object - * @param element the object to realAdd - * @return A new array containing the existing elements and the new element - * @throws IndexOutOfBoundsException if the index is out of range - * (index < 0 || index > array.length). - */ - @NonNull - public static T[] add(@Nullable T[] array, int index, @Nullable T element) { - Class clss; - if (array != null) { - clss = array.getClass().getComponentType(); - } else if (element != null) { - clss = element.getClass(); - } else { - return (T[]) new Object[]{null}; - } - return (T[]) realAdd(array, index, element, clss); - } - - @NonNull - public static boolean[] add(@Nullable boolean[] array, int index, boolean element) { - return (boolean[]) realAdd(array, index, element, Boolean.TYPE); - } - - @NonNull - public static char[] add(@Nullable char[] array, int index, char element) { - return (char[]) realAdd(array, index, element, Character.TYPE); - } - - @NonNull - public static byte[] add(@Nullable byte[] array, int index, byte element) { - return (byte[]) realAdd(array, index, element, Byte.TYPE); - } - - @NonNull - public static short[] add(@Nullable short[] array, int index, short element) { - return (short[]) realAdd(array, index, element, Short.TYPE); - } - - @NonNull - public static int[] add(@Nullable int[] array, int index, int element) { - return (int[]) realAdd(array, index, element, Integer.TYPE); - } - - @NonNull - public static long[] add(@Nullable long[] array, int index, long element) { - return (long[]) realAdd(array, index, element, Long.TYPE); - } - - @NonNull - public static float[] add(@Nullable float[] array, int index, float element) { - return (float[]) realAdd(array, index, element, Float.TYPE); - } - - @NonNull - public static double[] add(@Nullable double[] array, int index, double element) { - return (double[]) realAdd(array, index, element, Double.TYPE); - } - - @NonNull - private static Object realAdd(@Nullable Object array, int index, @Nullable Object element, Class clss) { - if (array == null) { - if (index != 0) { - throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0"); - } - Object joinedArray = Array.newInstance(clss, 1); - Array.set(joinedArray, 0, element); - return joinedArray; - } - int length = Array.getLength(array); - if (index > length || index < 0) { - throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); - } - Object result = Array.newInstance(clss, length + 1); - System.arraycopy(array, 0, result, 0, index); - Array.set(result, index, element); - if (index < length) { - System.arraycopy(array, index, result, index + 1, length - index); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // remove - /////////////////////////////////////////////////////////////////////////// - - /** - *

Removes the element at the specified position from the specified array. - * All subsequent elements are shifted to the left (substracts one from - * their indices).

- * - *

This method returns a new array with the same elements of the input - * array except the element on the specified position. The component - * type of the returned array is always the same as that of the input - * array.

- * - *

If the input array is null, an IndexOutOfBoundsException - * will be thrown, because in that case no valid index can be specified.

- * - *
-     * ArrayUtils.remove(["a"], 0)           = []
-     * ArrayUtils.remove(["a", "b"], 0)      = ["b"]
-     * ArrayUtils.remove(["a", "b"], 1)      = ["a"]
-     * ArrayUtils.remove(["a", "b", "c"], 1) = ["a", "c"]
-     * 
- * - * @param array the array to remove the element from, may be null - * @param index the position of the element to be removed - * @return A new array containing the existing elements except the element - * at the specified position. - * @throws IndexOutOfBoundsException if the index is out of range - * (index < 0 || index >= array.length) - */ - @Nullable - public static Object[] remove(@Nullable Object[] array, int index) { - if (array == null) return null; - return (Object[]) remove((Object) array, index); - } - - /** - *

Removes the first occurrence of the specified element from the - * specified array. All subsequent elements are shifted to the left - * (substracts one from their indices). If the array doesn't contains - * such an element, no elements are removed from the array.

- * - *

This method returns a new array with the same elements of the input - * array except the first occurrence of the specified element. The component - * type of the returned array is always the same as that of the input - * array.

- * - *
-     * ArrayUtils.removeElement(null, "a")            = null
-     * ArrayUtils.removeElement([], "a")              = []
-     * ArrayUtils.removeElement(["a"], "b")           = ["a"]
-     * ArrayUtils.removeElement(["a", "b"], "a")      = ["b"]
-     * ArrayUtils.removeElement(["a", "b", "a"], "a") = ["b", "a"]
-     * 
- * - * @param array the array to remove the element from, may be null - * @param element the element to be removed - * @return A new array containing the existing elements except the first - * occurrence of the specified element. - */ - @Nullable - public static Object[] removeElement(@Nullable Object[] array, @Nullable Object element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static boolean[] remove(@Nullable boolean[] array, int index) { - if (array == null) return null; - return (boolean[]) remove((Object) array, index); - } - - @Nullable - public static boolean[] removeElement(@Nullable boolean[] array, boolean element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static byte[] remove(@Nullable byte[] array, int index) { - if (array == null) return null; - return (byte[]) remove((Object) array, index); - } - - @Nullable - public static byte[] removeElement(@Nullable byte[] array, byte element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static char[] remove(@Nullable char[] array, int index) { - if (array == null) return null; - return (char[]) remove((Object) array, index); - } - - @Nullable - public static char[] removeElement(@Nullable char[] array, char element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static double[] remove(@Nullable double[] array, int index) { - if (array == null) return null; - return (double[]) remove((Object) array, index); - } - - @Nullable - public static double[] removeElement(@Nullable double[] array, double element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - //noinspection ConstantConditions - return remove(array, index); - } - - @Nullable - public static float[] remove(@Nullable float[] array, int index) { - if (array == null) return null; - return (float[]) remove((Object) array, index); - } - - @Nullable - public static float[] removeElement(@Nullable float[] array, float element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static int[] remove(@Nullable int[] array, int index) { - if (array == null) return null; - return (int[]) remove((Object) array, index); - } - - @Nullable - public static int[] removeElement(@Nullable int[] array, int element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static long[] remove(@Nullable long[] array, int index) { - if (array == null) return null; - return (long[]) remove((Object) array, index); - } - - @Nullable - public static long[] removeElement(@Nullable long[] array, long element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @Nullable - public static short[] remove(@Nullable short[] array, int index) { - if (array == null) return null; - return (short[]) remove((Object) array, index); - } - - @Nullable - public static short[] removeElement(@Nullable short[] array, short element) { - int index = indexOf(array, element); - if (index == INDEX_NOT_FOUND) { - return copy(array); - } - return remove(array, index); - } - - @NonNull - private static Object remove(@NonNull Object array, int index) { - int length = getLength(array); - if (index < 0 || index >= length) { - throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); - } - - Object result = Array.newInstance(array.getClass().getComponentType(), length - 1); - System.arraycopy(array, 0, result, 0, index); - if (index < length - 1) { - System.arraycopy(array, index + 1, result, index, length - index - 1); - } - - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // object indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable Object[] array, @Nullable Object objectToFind) { - return indexOf(array, objectToFind, 0); - } - - public static int indexOf(@Nullable Object[] array, @Nullable final Object objectToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - if (objectToFind == null) { - for (int i = startIndex; i < array.length; i++) { - if (array[i] == null) { - return i; - } - } - } else { - for (int i = startIndex; i < array.length; i++) { - if (objectToFind.equals(array[i])) { - return i; - } - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable Object[] array, @Nullable Object objectToFind) { - return lastIndexOf(array, objectToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable Object[] array, @Nullable Object objectToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - if (objectToFind == null) { - for (int i = startIndex; i >= 0; i--) { - if (array[i] == null) { - return i; - } - } - } else { - for (int i = startIndex; i >= 0; i--) { - if (objectToFind.equals(array[i])) { - return i; - } - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable Object[] array, @Nullable Object objectToFind) { - return indexOf(array, objectToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // long indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable long[] array, long valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable long[] array, long valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable long[] array, long valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable long[] array, long valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable long[] array, long valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // int indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable int[] array, int valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable int[] array, int valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable int[] array, int valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable int[] array, int valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable int[] array, int valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // short indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable short[] array, short valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable short[] array, short valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable short[] array, short valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable short[] array, short valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable short[] array, short valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // char indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable char[] array, char valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable char[] array, char valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable char[] array, char valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable char[] array, char valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable char[] array, char valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // byte indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable byte[] array, byte valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable byte[] array, byte valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable byte[] array, byte valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable byte[] array, byte valueToFind, int startIndex) { - if (array == null) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable byte[] array, byte valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // double indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable double[] array, double valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable double[] array, double valueToFind, double tolerance) { - return indexOf(array, valueToFind, 0, tolerance); - } - - public static int indexOf(@Nullable double[] array, double valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int indexOf(@Nullable double[] array, double valueToFind, int startIndex, double tolerance) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - double min = valueToFind - tolerance; - double max = valueToFind + tolerance; - for (int i = startIndex; i < array.length; i++) { - if (array[i] >= min && array[i] <= max) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable double[] array, double valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable double[] array, double valueToFind, double tolerance) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance); - } - - public static int lastIndexOf(@Nullable double[] array, double valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable double[] array, double valueToFind, int startIndex, double tolerance) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - double min = valueToFind - tolerance; - double max = valueToFind + tolerance; - for (int i = startIndex; i >= 0; i--) { - if (array[i] >= min && array[i] <= max) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable double[] array, double valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable double[] array, double valueToFind, double tolerance) { - return indexOf(array, valueToFind, 0, tolerance) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // float indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable float[] array, float valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable float[] array, float valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable float[] array, float valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable float[] array, float valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable float[] array, float valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // bool indexOf - /////////////////////////////////////////////////////////////////////////// - - public static int indexOf(@Nullable boolean[] array, boolean valueToFind) { - return indexOf(array, valueToFind, 0); - } - - public static int indexOf(@Nullable boolean[] array, boolean valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - for (int i = startIndex; i < array.length; i++) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static int lastIndexOf(@Nullable boolean[] array, boolean valueToFind) { - return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); - } - - public static int lastIndexOf(@Nullable boolean[] array, boolean valueToFind, int startIndex) { - if (ArrayUtils.isEmpty(array)) { - return INDEX_NOT_FOUND; - } - if (startIndex < 0) { - return INDEX_NOT_FOUND; - } else if (startIndex >= array.length) { - startIndex = array.length - 1; - } - for (int i = startIndex; i >= 0; i--) { - if (valueToFind == array[i]) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - public static boolean contains(@Nullable boolean[] array, boolean valueToFind) { - return indexOf(array, valueToFind) != INDEX_NOT_FOUND; - } - - /////////////////////////////////////////////////////////////////////////// - // char converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static char[] toPrimitive(@Nullable Character[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new char[0]; - } - final char[] result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].charValue(); - } - return result; - } - - @Nullable - public static char[] toPrimitive(@Nullable Character[] array, char valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new char[0]; - } - final char[] result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - Character b = array[i]; - result[i] = (b == null ? valueForNull : b.charValue()); - } - return result; - } - - @Nullable - public static Character[] toObject(@Nullable char[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Character[0]; - } - final Character[] result = new Character[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Character(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // long converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static long[] toPrimitive(@Nullable Long[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new long[0]; - } - final long[] result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].longValue(); - } - return result; - } - - @Nullable - public static long[] toPrimitive(@Nullable Long[] array, long valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new long[0]; - } - final long[] result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - Long b = array[i]; - result[i] = (b == null ? valueForNull : b.longValue()); - } - return result; - } - - @Nullable - public static Long[] toObject(@Nullable long[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Long[0]; - } - final Long[] result = new Long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Long(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // int converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static int[] toPrimitive(@Nullable Integer[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new int[0]; - } - final int[] result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].intValue(); - } - return result; - } - - @Nullable - public static int[] toPrimitive(@Nullable Integer[] array, int valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new int[0]; - } - final int[] result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - Integer b = array[i]; - result[i] = (b == null ? valueForNull : b.intValue()); - } - return result; - } - - @Nullable - public static Integer[] toObject(@Nullable int[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Integer[0]; - } - final Integer[] result = new Integer[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Integer(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // short converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static short[] toPrimitive(@Nullable Short[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new short[0]; - } - final short[] result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].shortValue(); - } - return result; - } - - @Nullable - public static short[] toPrimitive(@Nullable Short[] array, short valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new short[0]; - } - final short[] result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - Short b = array[i]; - result[i] = (b == null ? valueForNull : b.shortValue()); - } - return result; - } - - @Nullable - public static Short[] toObject(@Nullable short[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Short[0]; - } - final Short[] result = new Short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Short(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // byte converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static byte[] toPrimitive(@Nullable Byte[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new byte[0]; - } - final byte[] result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].byteValue(); - } - return result; - } - - @Nullable - public static byte[] toPrimitive(@Nullable Byte[] array, byte valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new byte[0]; - } - final byte[] result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - Byte b = array[i]; - result[i] = (b == null ? valueForNull : b.byteValue()); - } - return result; - } - - @Nullable - public static Byte[] toObject(@Nullable byte[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Byte[0]; - } - final Byte[] result = new Byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Byte(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // double converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static double[] toPrimitive(@Nullable Double[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new double[0]; - } - final double[] result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].doubleValue(); - } - return result; - } - - @Nullable - public static double[] toPrimitive(@Nullable Double[] array, double valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new double[0]; - } - final double[] result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - Double b = array[i]; - result[i] = (b == null ? valueForNull : b.doubleValue()); - } - return result; - } - - @Nullable - public static Double[] toObject(@Nullable double[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Double[0]; - } - final Double[] result = new Double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Double(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // float converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static float[] toPrimitive(@Nullable Float[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new float[0]; - } - final float[] result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].floatValue(); - } - return result; - } - - @Nullable - public static float[] toPrimitive(@Nullable Float[] array, float valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new float[0]; - } - final float[] result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - Float b = array[i]; - result[i] = (b == null ? valueForNull : b.floatValue()); - } - return result; - } - - @Nullable - public static Float[] toObject(@Nullable float[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Float[0]; - } - final Float[] result = new Float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = new Float(array[i]); - } - return result; - } - - /////////////////////////////////////////////////////////////////////////// - // boolean converters - /////////////////////////////////////////////////////////////////////////// - - @Nullable - public static boolean[] toPrimitive(@Nullable Boolean[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new boolean[0]; - } - final boolean[] result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i].booleanValue(); - } - return result; - } - - @Nullable - public static boolean[] toPrimitive(@Nullable Boolean[] array, boolean valueForNull) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new boolean[0]; - } - final boolean[] result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - Boolean b = array[i]; - result[i] = (b == null ? valueForNull : b.booleanValue()); - } - return result; - } - - @Nullable - public static Boolean[] toObject(@Nullable boolean[] array) { - if (array == null) { - return null; - } else if (array.length == 0) { - return new Boolean[0]; - } - final Boolean[] result = new Boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (array[i] ? Boolean.TRUE : Boolean.FALSE); - } - return result; - } - - @NonNull - public static List asList(@Nullable T... array) { - if (array == null || array.length == 0) { - return Collections.emptyList(); - } - return Arrays.asList(array); - } - - @NonNull - public static List asUnmodifiableList(@Nullable T... array) { - return Collections.unmodifiableList(asList(array)); - } - - @NonNull - public static List asArrayList(@Nullable T... array) { - List list = new ArrayList<>(); - if (array == null || array.length == 0) return list; - list.addAll(Arrays.asList(array)); - return list; - } - - @NonNull - public static List asLinkedList(@Nullable T... array) { - List list = new LinkedList<>(); - if (array == null || array.length == 0) return list; - list.addAll(Arrays.asList(array)); - return list; - } - - public static void sort(@Nullable T[] array, Comparator c) { - if (array == null || array.length < 2) return; - Arrays.sort(array, c); - } - - public static void sort(@Nullable byte[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable char[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable double[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable float[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable int[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable long[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - public static void sort(@Nullable short[] array) { - if (array == null || array.length < 2) return; - Arrays.sort(array); - } - - /** - * Executes the given closure on each element in the array. - *

- * If the input array or closure is null, there is no change made. - * - * @param array The array. - * @param closure the closure to perform, may be null - */ - public static void forAllDo(@Nullable Object array, @Nullable Closure closure) { - if (array == null || closure == null) return; - if (array instanceof Object[]) { - Object[] objects = (Object[]) array; - for (int i = 0, length = objects.length; i < length; i++) { - Object ele = objects[i]; - closure.execute(i, (E) ele); - } - } else if (array instanceof boolean[]) { - boolean[] booleans = (boolean[]) array; - for (int i = 0, length = booleans.length; i < length; i++) { - boolean ele = booleans[i]; - closure.execute(i, (E) (ele ? Boolean.TRUE : Boolean.FALSE)); - } - } else if (array instanceof byte[]) { - byte[] bytes = (byte[]) array; - for (int i = 0, length = bytes.length; i < length; i++) { - byte ele = bytes[i]; - closure.execute(i, (E) Byte.valueOf(ele)); - } - } else if (array instanceof char[]) { - char[] chars = (char[]) array; - for (int i = 0, length = chars.length; i < length; i++) { - char ele = chars[i]; - closure.execute(i, (E) Character.valueOf(ele)); - } - } else if (array instanceof short[]) { - short[] shorts = (short[]) array; - for (int i = 0, length = shorts.length; i < length; i++) { - short ele = shorts[i]; - closure.execute(i, (E) Short.valueOf(ele)); - } - } else if (array instanceof int[]) { - int[] ints = (int[]) array; - for (int i = 0, length = ints.length; i < length; i++) { - int ele = ints[i]; - closure.execute(i, (E) Integer.valueOf(ele)); - } - } else if (array instanceof long[]) { - long[] longs = (long[]) array; - for (int i = 0, length = longs.length; i < length; i++) { - long ele = longs[i]; - closure.execute(i, (E) Long.valueOf(ele)); - } - } else if (array instanceof float[]) { - float[] floats = (float[]) array; - for (int i = 0, length = floats.length; i < length; i++) { - float ele = floats[i]; - closure.execute(i, (E) Float.valueOf(ele)); - } - } else if (array instanceof double[]) { - double[] doubles = (double[]) array; - for (int i = 0, length = doubles.length; i < length; i++) { - double ele = doubles[i]; - closure.execute(i, (E) Double.valueOf(ele)); - } - } else { - throw new IllegalArgumentException("Not an array: " + array.getClass()); - } - } - - /** - * Return the string of array. - * - * @param array The array. - * @return the string of array - */ - @NonNull - public static String toString(@Nullable Object array) { - if (array == null) return "null"; - if (array instanceof Object[]) { - return Arrays.deepToString((Object[]) array); - } else if (array instanceof boolean[]) { - return Arrays.toString((boolean[]) array); - } else if (array instanceof byte[]) { - return Arrays.toString((byte[]) array); - } else if (array instanceof char[]) { - return Arrays.toString((char[]) array); - } else if (array instanceof double[]) { - return Arrays.toString((double[]) array); - } else if (array instanceof float[]) { - return Arrays.toString((float[]) array); - } else if (array instanceof int[]) { - return Arrays.toString((int[]) array); - } else if (array instanceof long[]) { - return Arrays.toString((long[]) array); - } else if (array instanceof short[]) { - return Arrays.toString((short[]) array); - } - throw new IllegalArgumentException("Array has incompatible type: " + array.getClass()); - } - - public interface Closure { - void execute(int index, E item); - } -} diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/AssetsUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/AssetsUtils.java deleted file mode 100644 index 9199638ded..0000000000 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/AssetsUtils.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.mogo.eagle.core.utilcode.util; - -import android.content.Context; -import android.text.TextUtils; -import android.util.Log; - -import java.io.BufferedInputStream; -import java.io.InputStream; - -/** - * @author congtaowang - * @since 2019-12-12 - *

- * 读取asset文件 - */ -public class AssetsUtils { - - private static final String TAG = "amap.AssetsUtils"; - - public static byte[] read( Context context, String fileName ) { - if ( context == null || TextUtils.isEmpty( fileName ) ) { - return null; - } - byte[] buffer = null; - try { - InputStream is = context.getAssets().open( fileName ); - BufferedInputStream bis = new BufferedInputStream( is ); - buffer = new byte[is.available()]; - bis.read( buffer ); - bis.close(); - is.close(); - Log.d( TAG, "read assets success: " + fileName + " size=" + buffer.length ); - } catch ( Exception e ) { - e.printStackTrace(); - } - return buffer; - } -} diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/BitmapHelper.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/BitmapHelper.java index e4fbc80f0d..aa4f403338 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/BitmapHelper.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/BitmapHelper.java @@ -53,9 +53,6 @@ public class BitmapHelper { /** * 根据原图添加圆角 - * - * @param source - * @return */ public static Bitmap createRoundCornerImage( Bitmap source, float corner ) { final Paint paint = new Paint(); @@ -75,7 +72,7 @@ public class BitmapHelper { } ByteArrayOutputStream bos = null; - byte[] result = null; + byte[] result; try { bos = new ByteArrayOutputStream(); @@ -150,7 +147,7 @@ public class BitmapHelper { } listener.onBeforeCompress(); ByteArrayOutputStream bos = null; - Bitmap target = null; + Bitmap target; try { bos = new ByteArrayOutputStream(); @@ -164,15 +161,11 @@ public class BitmapHelper { byte[] result = bos.toByteArray(); target = bytesToBitmap( result ); - if ( listener != null ) { - listener.onCompressSuccess( result ); - } + listener.onCompressSuccess( result ); } catch ( Exception e ) { e.printStackTrace(); target = null; - if ( listener != null ) { - listener.onCompressFailed( "压缩失败" ); - } + listener.onCompressFailed( "压缩失败" ); } finally { IOUtils.closeSilently( bos ); } @@ -203,7 +196,6 @@ public class BitmapHelper { target = bytesToBitmap( result ); } catch ( Exception e ) { e.printStackTrace(); - target = null; } finally { IOUtils.closeSilently( bos ); } @@ -630,26 +622,19 @@ public class BitmapHelper { */ public static Bitmap getVideoThumbnail( String filePath ) { Bitmap b = null; - MediaMetadataRetriever retriever = new MediaMetadataRetriever(); + MediaMetadataRetriever retriever = null; try { retriever = new MediaMetadataRetriever(); - if (Build.VERSION.SDK_INT >= 14) - retriever.setDataSource(filePath, new HashMap()); - else - retriever.setDataSource(filePath); - // mediaMetadataRetriever.setDataSource(videoPath); + retriever.setDataSource(filePath, new HashMap<>()); b = retriever.getFrameAtTime(); - } catch ( IllegalArgumentException e ) { - e.printStackTrace(); } catch ( RuntimeException e ) { e.printStackTrace(); - } finally { try { - retriever.release(); - } catch ( RuntimeException e ) { - e.printStackTrace(); - } catch (IOException e) { + if(retriever != null){ + retriever.release(); + } + } catch ( RuntimeException | IOException e ) { e.printStackTrace(); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CollectionUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CollectionUtils.java index 3babaa0035..efe9993ad9 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CollectionUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CollectionUtils.java @@ -61,9 +61,7 @@ public final class CollectionUtils { public static ArrayList newArrayList(E... array) { ArrayList list = new ArrayList<>(); if (array == null || array.length == 0) return list; - for (E e : array) { - list.add(e); - } + list.addAll(Arrays.asList(array)); return list; } @@ -82,9 +80,7 @@ public final class CollectionUtils { public static LinkedList newLinkedList(E... array) { LinkedList list = new LinkedList<>(); if (array == null || array.length == 0) return list; - for (E e : array) { - list.add(e); - } + list.addAll(Arrays.asList(array)); return list; } @@ -103,9 +99,7 @@ public final class CollectionUtils { public static HashSet newHashSet(E... array) { HashSet set = new HashSet<>(); if (array == null || array.length == 0) return set; - for (E e : array) { - set.add(e); - } + set.addAll(Arrays.asList(array)); return set; } @@ -124,9 +118,7 @@ public final class CollectionUtils { public static TreeSet newTreeSet(Comparator comparator, E... array) { TreeSet set = new TreeSet<>(comparator); if (array == null || array.length == 0) return set; - for (E e : array) { - set.add(e); - } + set.addAll(Arrays.asList(array)); return set; } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ColorUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ColorUtils.java index de5e46b6d3..587786a1c0 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ColorUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ColorUtils.java @@ -307,12 +307,12 @@ public final class ColorUtils { int[] cColor = hexToArgb(centerColor); int[] eColor = hexToArgb(endColor); if (step >= 3) { - int colorStep = (int) Math.floor(step/2); + int colorStep = (int) Math.floor(step/2.0f); // 计算每一步的差值 - float aStep = (cColor[0] - sColor[0]) / colorStep; - float rStep = (cColor[1] - sColor[1]) / colorStep; - float gStep = (cColor[2] - sColor[2]) / colorStep; - float bStep = (cColor[3] - sColor[3]) / colorStep; + float aStep = (float) (cColor[0] - sColor[0]) / colorStep; + float rStep = (float) (cColor[1] - sColor[1]) / colorStep; + float gStep = (float) (cColor[2] - sColor[2]) / colorStep; + float bStep = (float) (cColor[3] - sColor[3]) / colorStep; for (int i = 0; i < colorStep; i++) { @@ -322,10 +322,10 @@ public final class ColorUtils { (int)(gStep * i + sColor[2]), (int)(bStep * i + sColor[3]))); } - float aStep_ = (eColor[0] - cColor[0]) / colorStep; - float rStep_ = (eColor[1] - cColor[1]) / colorStep; - float gStep_ = (eColor[2] - cColor[2]) / colorStep; - float bStep_ = (eColor[3] - cColor[3]) / colorStep; + float aStep_ = (float) (eColor[0] - cColor[0]) / colorStep; + float rStep_ = (float) (eColor[1] - cColor[1]) / colorStep; + float gStep_ = (float) (eColor[2] - cColor[2]) / colorStep; + float bStep_ = (float) (eColor[3] - cColor[3]) / colorStep; for (int i = 0; i < colorStep; i++) { gradientColorArr.add( diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ConvertUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ConvertUtils.java index 5b2f3a420a..141cb066c8 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ConvertUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ConvertUtils.java @@ -578,7 +578,12 @@ public final class ConvertUtils { */ public static byte[] inputStream2Bytes(final InputStream is) { if (is == null) return null; - return input2OutputStream(is).toByteArray(); + ByteArrayOutputStream byteArrayOutputStream = input2OutputStream(is); + if(byteArrayOutputStream != null){ + return byteArrayOutputStream.toByteArray(); + }else{ + return null; + } } /** @@ -772,14 +777,14 @@ public final class ConvertUtils { SpannableStringBuilder spannable = new SpannableStringBuilder(); int length = value.length(); if (length > 1) { - /** + /* * 对于长度大于1的数,对首位进行赋值; * 对于两位数: 如果首位为“1”,则拼接的字符串为“”; */ - spannable.append(getChinese(number / (int) Math.pow(10, length - 1), length)) + spannable.append(getChinese(number / (int) Math.pow(10.0f, length - 1.0f), length)) .append(getUnitChinese(length)); // 如果该数值取余数为0,则直接返回已有字符(例如:100,直接返回一百) - if (number % (int) Math.pow(10, length - 1) == 0) { + if (number % (int) Math.pow(10.0f, length - 1.0f) == 0) { return spannable.toString(); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CoordinateUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CoordinateUtils.java index ffe4576d6d..e761fe2a25 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CoordinateUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/CoordinateUtils.java @@ -3,6 +3,7 @@ package com.mogo.eagle.core.utilcode.util; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; +import java.math.RoundingMode; /** * @author donghongyu @@ -10,10 +11,6 @@ import java.math.BigDecimal; public class CoordinateUtils { /** - * @param lon1 - * @param lat1 - * @param lon2 - * @param lat2 * @return 两坐标的距离 单位:米(M) */ public static float calculateLineDistance( double lon1, double lat1, double lon2, double lat2 ) { @@ -56,11 +53,11 @@ public class CoordinateUtils { private static final double a = 6378245.0D; private static final double ee = 0.006693421622965943D; - public static final boolean outOfChina( double lat, double lng ) { + public static boolean outOfChina(double lat, double lng ) { return lng <= 73.66D || lng >= 135.05D || lat <= 3.86D || lat >= 53.55D; } - private static final double transformLat( double lng, double lat ) { + private static double transformLat(double lng, double lat ) { double ret = -100.0D + 2.0D * lng + 3.0D * lat + 0.2D * lat * lat + 0.1D * lng * lat + 0.2D * Math.sqrt( Math.abs( lng ) ); ret += ( 20.0D * Math.sin( 6.0D * lng * 3.141592653589793D ) + 20.0D * Math.sin( 2.0D * lng * 3.141592653589793D ) ) * 2.0D / 3.0D; ret += ( 20.0D * Math.sin( lat * 3.141592653589793D ) + 40.0D * Math.sin( lat / 3.0D * 3.141592653589793D ) ) * 2.0D / 3.0D; @@ -68,7 +65,7 @@ public class CoordinateUtils { return ret; } - private static final double transformLon( double lng, double lat ) { + private static double transformLon(double lng, double lat ) { double ret = 300.0D + lng + 2.0D * lat + 0.1D * lng * lng + 0.1D * lng * lat + 0.1D * Math.sqrt( Math.abs( lng ) ); ret += ( 20.0D * Math.sin( 6.0D * lng * 3.141592653589793D ) + 20.0D * Math.sin( 2.0D * lng * 3.141592653589793D ) ) * 2.0D / 3.0D; ret += ( 20.0D * Math.sin( lng * 3.141592653589793D ) + 40.0D * Math.sin( lng / 3.0D * 3.141592653589793D ) ) * 2.0D / 3.0D; @@ -78,12 +75,11 @@ public class CoordinateUtils { @NotNull // World Geodetic System ==> Mars Geodetic System - public static final double[] transformWgsToGcj( double wgLat, double wgLon ) { + public static double[] transformWgsToGcj(double wgLat, double wgLon ) { double[] point = new double[2]; if ( outOfChina( wgLat, wgLon ) ) { point[0] = wgLon; point[1] = wgLat; - return point; } else { double dLat = transformLat( wgLon - 105.0D, wgLat - 35.0D ); double dLon = transformLon( wgLon - 105.0D, wgLat - 35.0D ); @@ -97,12 +93,12 @@ public class CoordinateUtils { double mgLon = wgLon + dLon; point[0] = dealRound( mgLon ); point[1] = dealRound( mgLat ); - return point; } + return point; } @NotNull - public static final double[] transformGcj02toWgs84( double lat, double lng ) { + public static double[] transformGcj02toWgs84(double lat, double lng ) { double[] var10000; if ( outOfChina( lat, lng ) ) { var10000 = new double[]{lng, lat}; @@ -123,10 +119,9 @@ public class CoordinateUtils { return var10000; } - private static final double dealRound( double value ) { - BigDecimal bg = new BigDecimal( value ); - double result = bg.setScale( 6, 4 ).doubleValue(); - return result; + private static double dealRound(double value ) { + BigDecimal bg = BigDecimal.valueOf( value ); + return bg.setScale( 6, RoundingMode.HALF_UP).doubleValue(); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DateTimeUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DateTimeUtils.java index bc27bf1209..9c2f240976 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DateTimeUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DateTimeUtils.java @@ -45,6 +45,9 @@ public class DateTimeUtils { public static Calendar cleanCalendarTime( Calendar c) { + if(c == null){ + return null; + } c.set( Calendar.HOUR_OF_DAY, 0); c.set( Calendar.MINUTE, 0); c.set( Calendar.SECOND, 0); @@ -54,10 +57,6 @@ public class DateTimeUtils { /** * 获得指定日期表示格式转换成Calendar的格式 - * - * @param src - * @param fallback 若无法转换,返回一个默认值 - * @return */ public static Calendar getCalendar( T src, Calendar fallback) { if (src != null) { @@ -101,7 +100,7 @@ public class DateTimeUtils { return getCalendarByPatterns(nSrc, PATTERNS); } catch ( Exception e) { try { - calendar.setTimeInMillis( Long.valueOf(nSrc)); + calendar.setTimeInMillis( Long.parseLong(nSrc)); } catch ( NumberFormatException e1) { throw new IllegalArgumentException(e1); } @@ -134,11 +133,6 @@ public class DateTimeUtils { /** * 匹配pattern获得时间,若无法解析抛出异常 - * - * @param dateTimeStr - * @param patternStr - * @return - * @throws IllegalArgumentException */ public static Calendar getCalendarByPattern( String dateTimeStr, String patternStr) { try { @@ -156,11 +150,6 @@ public class DateTimeUtils { /** * 匹配pattern数组中的所有pattern解析时间格式,若没有可以解析的方式则抛出异常 - * - * @param dateTimeStr - * @param patternStr - * @return - * @throws IllegalArgumentException */ public static Calendar getCalendarByPatterns( String dateTimeStr, String[] patternStr) { for ( String string : patternStr) { @@ -208,8 +197,6 @@ public class DateTimeUtils { /** * login时server的日期 - * - * @return */ public static Calendar getLoginServerDate() { return getCalendar(tss); @@ -229,12 +216,8 @@ public class DateTimeUtils { /** * 获得时间间隔 - * - * @param from - * @param to * @param unit 时间间隔单位{@link DateTimeUtils#ONE_SECOND},{@link DateTimeUtils#ONE_MINUTE}, * {@link DateTimeUtils#ONE_HOUR}, {@link DateTimeUtils#ONE_DAY} - * @return */ public static long getIntervalTimes( Calendar from, Calendar to, long unit) { if (from == null || to == null) { @@ -245,12 +228,7 @@ public class DateTimeUtils { /** * 获得日期间隔 忽略小时 - * - * @param startdate - * @param enddate - * @return */ - public static int getIntervalDays( String startdate, String enddate, String pattern) { int betweenDays = 0; if (startdate == null || enddate == null) { @@ -264,15 +242,15 @@ public class DateTimeUtils { } public static int getIntervalDays(T from, T to) { - Calendar startdate = getCalendar(from); - Calendar enddate = getCalendar(to); - cleanCalendarTime(startdate); - cleanCalendarTime(enddate); - return (int) getIntervalTimes(startdate, enddate, ONE_DAY); + Calendar startDate = getCalendar(from); + Calendar endDate = getCalendar(to); + cleanCalendarTime(startDate); + cleanCalendarTime(endDate); + return (int) getIntervalTimes(startDate, endDate, ONE_DAY); } - private static String[] weekdays = {"", "周日", "周一", "周二", "周三", "周四", "周五", "周六",}; - private static String[] weekdays1 = {"", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六",}; + private static final String[] weekdays = {"", "周日", "周一", "周二", "周三", "周四", "周五", "周六",}; + private static final String[] weekdays1 = {"", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六",}; /** * calendar --> 周一~周日 @@ -310,12 +288,12 @@ public class DateTimeUtils { } // 是否到刷新时间 - public static boolean isRefersh(long beforeTime) { - return isRefersh(DATETIME_FIELD_REFERSH * 1000 * 60, beforeTime); + public static boolean isRefresh(long beforeTime) { + return isRefresh(DATETIME_FIELD_REFERSH * 1_000L * 60, beforeTime); } // 是否到刷新时间 - public static boolean isRefersh(long gap, long beforeTime) { + public static boolean isRefresh(long gap, long beforeTime) { return new Date().getTime() - beforeTime >= gap; } @@ -344,13 +322,7 @@ public class DateTimeUtils { } else if (c1.get( Calendar.MONTH) < c2.get( Calendar.MONTH)) { return -1; } else { - if (c1.get( Calendar.DAY_OF_MONTH) > c2.get( Calendar.DAY_OF_MONTH)) { - return 1; - } else if (c1.get( Calendar.DAY_OF_MONTH) < c2.get( Calendar.DAY_OF_MONTH)) { - return -1; - } else { - return 0; - } + return Integer.compare(c1.get(Calendar.DAY_OF_MONTH), c2.get(Calendar.DAY_OF_MONTH)); } } } @@ -359,14 +331,14 @@ public class DateTimeUtils { if ( TextUtils.isEmpty(HH_mm) || null == src) { return; } - String s[] = HH_mm.split(":"); + String[] s = HH_mm.split(":"); if (s.length != 2) { return; } try { cleanCalendarTime(src); - src.set( Calendar.HOUR_OF_DAY, Integer.valueOf(s[0])); - src.set( Calendar.MINUTE, Integer.valueOf(s[1])); + src.set( Calendar.HOUR_OF_DAY, Integer.parseInt(s[0])); + src.set( Calendar.MINUTE, Integer.parseInt(s[1])); } catch ( NumberFormatException e) { } @@ -394,8 +366,7 @@ public class DateTimeUtils { Calendar a = Calendar.getInstance(); a.set( Calendar.DATE, 1); a.roll( Calendar.DATE, -1); - int maxDate = a.get( Calendar.DATE); - return maxDate; + return a.get( Calendar.DATE); } public static String convertToChineseWeekNumber( int number) { @@ -444,22 +415,18 @@ public class DateTimeUtils { /** * 获取 06月07 格式的日期 * @param timestamp 时间戳 - * @return */ public static String getTimeText( long timestamp, String dateFormat) { SimpleDateFormat format = new SimpleDateFormat(dateFormat, Locale.US); - String strStart = format.format(new Date(timestamp)); - return strStart; + return format.format(new Date(timestamp)); } /** * 获取 06月07 格式的日期 - * @return */ public static String getTimeText(String dateFormat) { SimpleDateFormat format = new SimpleDateFormat(dateFormat, Locale.US); - String strStart = format.format(new Date()); - return strStart; + return format.format(new Date()); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceIdUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceIdUtils.java index 8bfe7fe99e..06a457b844 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceIdUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceIdUtils.java @@ -39,11 +39,7 @@ public final class DeviceIdUtils { if (TextUtils.isEmpty(deviceId)) { deviceId = getDeviceIdInternal(appContext); if (TextUtils.isEmpty(deviceId)) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) { - deviceId = ((TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber(); - } - } else { + if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) { deviceId = ((TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber(); } if (TextUtils.isEmpty(deviceId)) { @@ -65,10 +61,8 @@ public final class DeviceIdUtils { private static String getDeviceIdInternal(Context context) { String id = ""; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { - return id; - } + if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { + return id; } TelephonyManager telephonymanager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); @@ -100,13 +94,7 @@ public final class DeviceIdUtils { method.setAccessible(true); } serial = (String) method.invoke(new Build(), "ro.serialno"); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { + } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } return serial; diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceUtils.java index 3134cc5b38..a2dea6cc72 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceUtils.java @@ -24,7 +24,6 @@ import android.telephony.gsm.GsmCellLocation; import android.text.TextUtils; import android.util.Log; -import androidx.annotation.RequiresApi; import androidx.annotation.RequiresPermission; import java.io.BufferedReader; @@ -75,7 +74,6 @@ public final class DeviceUtils { * * @return {@code true}: yes
{@code false}: no */ - @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) public static boolean isAdbEnabled() { return Settings.Secure.getInt( Utils.getApp().getContentResolver(), @@ -277,7 +275,7 @@ public final class DeviceUtils { InetAddress inetAddress = addresses.nextElement(); if (!inetAddress.isLoopbackAddress()) { String hostAddress = inetAddress.getHostAddress(); - if (hostAddress.indexOf(':') < 0) return inetAddress; + if (hostAddress != null && hostAddress.indexOf(':') < 0) return inetAddress; } } } @@ -345,14 +343,7 @@ public final class DeviceUtils { * @return an ordered list of ABIs supported by this device */ public static String[] getABIs() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - return Build.SUPPORTED_ABIS; - } else { - if (!TextUtils.isEmpty(Build.CPU_ABI2)) { - return new String[]{Build.CPU_ABI, Build.CPU_ABI2}; - } - return new String[]{Build.CPU_ABI}; - } + return Build.SUPPORTED_ABIS; } /** @@ -391,20 +382,17 @@ public final class DeviceUtils { operatorName = name; } } - boolean checkOperatorName = operatorName.toLowerCase().equals("android"); + boolean checkOperatorName = operatorName.equalsIgnoreCase("android"); if (checkOperatorName) return true; String url = "tel:" + "123456"; Intent intent = new Intent(); intent.setData(Uri.parse(url)); intent.setAction(Intent.ACTION_DIAL); - boolean checkDial = intent.resolveActivity(Utils.getApp().getPackageManager()) == null; - if (checkDial) return true; + return intent.resolveActivity(Utils.getApp().getPackageManager()) == null; // boolean checkDebuggerConnected = Debug.isDebuggerConnected(); // if (checkDebuggerConnected) return true; - - return false; } /** @@ -412,7 +400,6 @@ public final class DeviceUtils { * * @return whether user has enabled development settings. */ - @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) public static boolean isDevelopmentSettingsEnabled() { return Settings.Global.getInt( Utils.getApp().getContentResolver(), @@ -497,8 +484,8 @@ public final class DeviceUtils { if (!TextUtils.isEmpty(androidId)) { return saveUdid(prefix + 2, androidId); } - } catch (Exception ignore) { - ignore.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); } return saveUdid(prefix + 9, ""); } @@ -565,8 +552,8 @@ public final class DeviceUtils { // Gsm网络 , 联通移动的网络属于这一套 if (location instanceof GsmCellLocation) { GsmCellLocation gsmLoc = (GsmCellLocation) location; - int cellid = gsmLoc.getCid(); - return String.valueOf(cellid); + int cellId = gsmLoc.getCid(); + return String.valueOf(cellId); // Cdma网络 , 电信网络属于这一种 } else if (location instanceof CdmaCellLocation) { CdmaCellLocation cdmaLoc = (CdmaCellLocation) location; @@ -584,18 +571,13 @@ public final class DeviceUtils { public static boolean isLocationEnabled() { int locationMode = 0; String locationProviders; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - try { - locationMode = Settings.Secure.getInt(Utils.getApp().getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_MODE); - } catch (Settings.SettingNotFoundException e) { - e.printStackTrace(); - return false; - } - return locationMode != Settings.Secure.LOCATION_MODE_OFF; - } else { - locationProviders = Settings.Secure.getString(Utils.getApp().getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); - return !TextUtils.isEmpty(locationProviders); + try { + locationMode = Settings.Secure.getInt(Utils.getApp().getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_MODE); + } catch (Settings.SettingNotFoundException e) { + e.printStackTrace(); + return false; } + return locationMode != Settings.Secure.LOCATION_MODE_OFF; } @@ -678,8 +660,8 @@ public final class DeviceUtils { } - private static String getSerialnoNumbers() { - final String serialnoStr = "[ro.boot.serialno]"; + private static String getSerialNoNumbers() { + final String serialNoStr = "[ro.boot.serialno]"; try { Process p = Runtime.getRuntime().exec("getprop"); p.waitFor(); @@ -687,20 +669,20 @@ public final class DeviceUtils { p.getInputStream())); String temp = ""; while ((temp = stdInput.readLine()) != null) { - Log.i("getSerialnoNumbers", temp); - if (temp.contains(serialnoStr)) { - temp.replaceAll(" ", ""); - int index = temp.indexOf(serialnoStr); + Log.i("getSerialNoNumbers", temp); + if (temp.contains(serialNoStr)) { + temp = temp.replaceAll(" ", ""); + int index = temp.indexOf(serialNoStr); temp = temp.substring(index + 20); temp = temp.substring(1, temp.length() - 1); - Log.d("getSerialnoNumbers", temp); + Log.d("getSerialNoNumbers", temp); return temp; } } - } catch (IOException | InterruptedException e) { + } catch (InterruptedException | IOException e) { e.printStackTrace(); } - return serialnoStr; + return serialNoStr; } public static final String KEY_DEVICE_ID = "deviceId"; diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/EncryptUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/EncryptUtils.java index 9efcc380dc..472a1e5a77 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/EncryptUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/EncryptUtils.java @@ -175,7 +175,7 @@ public final class EncryptUtils { public static byte[] encryptMD5File(final File file) { if (file == null) return null; FileInputStream fis = null; - DigestInputStream digestInputStream; + DigestInputStream digestInputStream = null; try { fis = new FileInputStream(file); MessageDigest md = MessageDigest.getInstance("MD5"); @@ -191,6 +191,9 @@ public final class EncryptUtils { return null; } finally { try { + if (digestInputStream != null) { + digestInputStream.close(); + } if (fis != null) { fis.close(); } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/FileUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/FileUtils.java index a9b26d8fce..3016a6c36a 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/FileUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/FileUtils.java @@ -1091,7 +1091,7 @@ public final class FileUtils { is = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024]; int readChars; - if (LINE_SEP.endsWith("\n")) { + if (LINE_SEP != null && LINE_SEP.endsWith("\n")) { while ((readChars = is.read(buffer, 0, 1024)) != -1) { for (int i = 0; i < readChars; ++i) { if (buffer[i] == '\n') ++count; @@ -1442,13 +1442,8 @@ public final class FileUtils { StatFs statFs = new StatFs(anyPathInFs); long blockSize; long totalSize; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { - blockSize = statFs.getBlockSizeLong(); - totalSize = statFs.getBlockCountLong(); - } else { - blockSize = statFs.getBlockSize(); - totalSize = statFs.getBlockCount(); - } + blockSize = statFs.getBlockSizeLong(); + totalSize = statFs.getBlockCountLong(); return blockSize * totalSize; } @@ -1463,13 +1458,8 @@ public final class FileUtils { StatFs statFs = new StatFs(anyPathInFs); long blockSize; long availableSize; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { - blockSize = statFs.getBlockSizeLong(); - availableSize = statFs.getAvailableBlocksLong(); - } else { - blockSize = statFs.getBlockSize(); - availableSize = statFs.getAvailableBlocks(); - } + blockSize = statFs.getBlockSizeLong(); + availableSize = statFs.getAvailableBlocksLong(); return blockSize * availableSize; } @@ -1558,8 +1548,6 @@ public final class FileUtils { byte[] bytes = new byte[in.available()]; int length = in.read(bytes); base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT); - } catch (FileNotFoundException e) { - e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { @@ -1709,53 +1697,49 @@ public final class FileUtils { * @param listener */ public static void copy(final InputStream is, final String to, final FileCopyListener listener) { - new Thread(new Runnable() { - @Override - public void run() { - Log.w("FileUtils", "======copy======"); + new Thread(() -> { + Log.w("FileUtils", "======copy======"); - if (listener != null) { - listener.onStart(); + if (listener != null) { + listener.onStart(); + } + + try { + + long fileSize = is.available(); + long process = 0; + + byte[] buff = new byte[1024]; + int rc = 0; + + File toFile = new File(to); + if (toFile.getParentFile() != null && !toFile.getParentFile().exists()) { + toFile.getParentFile().mkdirs(); } - try { + FileOutputStream fos = new FileOutputStream(toFile); - long fileSize = is.available(); - long process = 0; - - byte[] buff = new byte[1024]; - int rc = 0; - - File toFile = new File(to); - if (!toFile.getParentFile().exists()) { - toFile.getParentFile().mkdirs(); - } - - FileOutputStream fos = new FileOutputStream(toFile); - - while ((rc = is.read(buff, 0, 1024)) > 0) { - process += rc; - fos.write(buff, 0, rc); - if (listener != null) { - listener.onProcess(((int) (((float) process) * 100 / fileSize))); - } - } - - fos.flush(); - fos.close(); - is.close(); - - } catch (Exception e) { + while ((rc = is.read(buff, 0, 1024)) > 0) { + process += rc; + fos.write(buff, 0, rc); if (listener != null) { - listener.onFail(e); - return; + listener.onProcess(((int) (((float) process) * 100 / fileSize))); } } + fos.flush(); + fos.close(); + is.close(); + } catch (Exception e) { if (listener != null) { - listener.onFinish(to); + listener.onFail(e); + return; } } + + if (listener != null) { + listener.onFinish(to); + } }).start(); } @@ -1767,74 +1751,71 @@ public final class FileUtils { * @param listener */ public static void copy(final String from, final String to, final FileCopyListener listener) { - new Thread(new Runnable() { - @Override - public void run() { - File file = null; - try { - file = new File(from); - } catch (Exception e) { - if (listener != null) { - listener.onFail(e); - } + new Thread(() -> { + File file = null; + try { + file = new File(from); + } catch (Exception e) { + if (listener != null) { + listener.onFail(e); + } + return; + } + if (!file.isFile()) { + if (listener != null) { + listener.onFail(new Exception(String.format("%s is not a file", from))); return; } - if (!file.isFile()) { - if (listener != null) { - listener.onFail(new Exception(String.format("%s is not a file", from))); - return; - } - } - if (!file.exists()) { - if (listener != null) { - listener.onFail(new FileNotFoundException(String.format("%s is not exists.", from))); - return; - } - } - + } + if (!file.exists()) { if (listener != null) { - listener.onStart(); + listener.onFail(new FileNotFoundException(String.format("%s is not exists.", from))); + return; + } + } + + if (listener != null) { + listener.onStart(); + } + + long fileSize = file.length(); + long process = 0; + + try { + FileInputStream fis = new FileInputStream(file); + + byte[] buff = new byte[1024]; + int rc = 0; + + File toFile = new File(to); + if (!toFile.getParentFile().exists()) { + toFile.getParentFile().mkdirs(); } - long fileSize = file.length(); - long process = 0; + FileOutputStream fos = new FileOutputStream(toFile); - try { - FileInputStream fis = new FileInputStream(file); - - byte[] buff = new byte[1024]; - int rc = 0; - - File toFile = new File(to); - if (!toFile.getParentFile().exists()) { - toFile.getParentFile().mkdirs(); - } - - FileOutputStream fos = new FileOutputStream(toFile); - - while ((rc = fis.read(buff, 0, 1024)) > 0) { - process += rc; - fos.write(buff, 0, rc); - if (listener != null) { - listener.onProcess(((int) (((float) process) * 100 / fileSize))); - } - } - - fos.flush(); - fos.close(); - fis.close(); - - } catch (Exception e) { + while ((rc = fis.read(buff, 0, 1024)) > 0) { + process += rc; + fos.write(buff, 0, rc); if (listener != null) { - listener.onFail(e); - return; + listener.onProcess(((int) (((float) process) * 100 / fileSize))); } } + fos.flush(); + fos.close(); + fis.close(); + + } catch (Exception e) { if (listener != null) { - listener.onFinish(to); + listener.onFail(e); + return; } } + + if (listener != null) { + listener.onFinish(to); + } }).start(); } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/LogUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/LogUtils.java deleted file mode 100644 index 44b37542d8..0000000000 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/LogUtils.java +++ /dev/null @@ -1,1231 +0,0 @@ -package com.mogo.eagle.core.utilcode.util; - -import android.content.ClipData; -import android.content.ComponentName; -import android.content.Intent; -import android.graphics.Rect; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.util.Log; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.Formatter; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; - -import androidx.annotation.IntDef; -import androidx.annotation.IntRange; -import androidx.annotation.RequiresApi; -import androidx.collection.SimpleArrayMap; - -/** - *

- *     author: Blankj
- *     blog  : http://blankj.com
- *     time  : 2016/09/21
- *     desc  : utils about log
- * 
- */ -public final class LogUtils { - - public static final int V = Log.VERBOSE; - public static final int D = Log.DEBUG; - public static final int I = Log.INFO; - public static final int W = Log.WARN; - public static final int E = Log.ERROR; - public static final int A = Log.ASSERT; - - @IntDef({V, D, I, W, E, A}) - @Retention(RetentionPolicy.SOURCE) - public @interface TYPE { - } - - private static final char[] T = new char[]{'V', 'D', 'I', 'W', 'E', 'A'}; - - private static final int FILE = 0x10; - private static final int JSON = 0x20; - private static final int XML = 0x30; - - private static final String FILE_SEP = System.getProperty("file.separator"); - private static final String LINE_SEP = System.getProperty("line.separator"); - private static final String TOP_CORNER = "┌"; - private static final String MIDDLE_CORNER = "├"; - private static final String LEFT_BORDER = "│ "; - private static final String BOTTOM_CORNER = "└"; - private static final String SIDE_DIVIDER = - "────────────────────────────────────────────────────────"; - private static final String MIDDLE_DIVIDER = - "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄"; - private static final String TOP_BORDER = TOP_CORNER + SIDE_DIVIDER + SIDE_DIVIDER; - private static final String MIDDLE_BORDER = MIDDLE_CORNER + MIDDLE_DIVIDER + MIDDLE_DIVIDER; - private static final String BOTTOM_BORDER = BOTTOM_CORNER + SIDE_DIVIDER + SIDE_DIVIDER; - private static final int MAX_LEN = 1100;// fit for Chinese character - private static final String NOTHING = "log nothing"; - private static final String NULL = "null"; - private static final String ARGS = "args"; - private static final String PLACEHOLDER = " "; - private static final Config CONFIG = new Config(); - - private static SimpleDateFormat simpleDateFormat; - - private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(); - - private static final SimpleArrayMap I_FORMATTER_MAP = new SimpleArrayMap<>(); - - private LogUtils() { - throw new UnsupportedOperationException("u can't instantiate me..."); - } - - public static Config getConfig() { - return CONFIG; - } - - public static void v(final Object... contents) { - log(V, CONFIG.getGlobalTag(), contents); - } - - public static void vTag(final String tag, final Object... contents) { - log(V, tag, contents); - } - - public static void d(final Object... contents) { - log(D, CONFIG.getGlobalTag(), contents); - } - - public static void dTag(final String tag, final Object... contents) { - log(D, tag, contents); - } - - public static void i(final Object... contents) { - log(I, CONFIG.getGlobalTag(), contents); - } - - public static void iTag(final String tag, final Object... contents) { - log(I, tag, contents); - } - - public static void w(final Object... contents) { - log(W, CONFIG.getGlobalTag(), contents); - } - - public static void wTag(final String tag, final Object... contents) { - log(W, tag, contents); - } - - public static void e(final Object... contents) { - log(E, CONFIG.getGlobalTag(), contents); - } - - public static void eTag(final String tag, final Object... contents) { - log(E, tag, contents); - } - - public static void a(final Object... contents) { - log(A, CONFIG.getGlobalTag(), contents); - } - - public static void aTag(final String tag, final Object... contents) { - log(A, tag, contents); - } - - public static void file(final Object content) { - log(FILE | D, CONFIG.getGlobalTag(), content); - } - - public static void file(@TYPE final int type, final Object content) { - log(FILE | type, CONFIG.getGlobalTag(), content); - } - - public static void file(final String tag, final Object content) { - log(FILE | D, tag, content); - } - - public static void file(@TYPE final int type, final String tag, final Object content) { - log(FILE | type, tag, content); - } - - public static void json(final Object content) { - log(JSON | D, CONFIG.getGlobalTag(), content); - } - - public static void json(@TYPE final int type, final Object content) { - log(JSON | type, CONFIG.getGlobalTag(), content); - } - - public static void json(final String tag, final Object content) { - log(JSON | D, tag, content); - } - - public static void json(@TYPE final int type, final String tag, final Object content) { - log(JSON | type, tag, content); - } - - public static void xml(final String content) { - log(XML | D, CONFIG.getGlobalTag(), content); - } - - public static void xml(@TYPE final int type, final String content) { - log(XML | type, CONFIG.getGlobalTag(), content); - } - - public static void xml(final String tag, final String content) { - log(XML | D, tag, content); - } - - public static void xml(@TYPE final int type, final String tag, final String content) { - log(XML | type, tag, content); - } - - public static void log(final int type, final String tag, final Object... contents) { - if (!CONFIG.isLogSwitch()) return; - final int type_low = type & 0x0f, type_high = type & 0xf0; - if (CONFIG.isLog2ConsoleSwitch() || CONFIG.isLog2FileSwitch() || type_high == FILE) { - if (type_low < CONFIG.mConsoleFilter && type_low < CONFIG.mFileFilter) return; - final TagHead tagHead = processTagAndHead(tag); - final String body = processBody(type_high, contents); - if (CONFIG.isLog2ConsoleSwitch() && type_high != FILE && type_low >= CONFIG.mConsoleFilter) { - print2Console(type_low, tagHead.tag, tagHead.consoleHead, body); - } - if ((CONFIG.isLog2FileSwitch() || type_high == FILE) && type_low >= CONFIG.mFileFilter) { - EXECUTOR.execute(new Runnable() { - @Override - public void run() { - print2File(type_low, tagHead.tag, tagHead.fileHead + body); - } - }); - } - } - } - - public static String getCurrentLogFilePath() { - return getCurrentLogFilePath(new Date()); - } - - public static List getLogFiles() { - String dir = CONFIG.getDir(); - File logDir = new File(dir); - if (!logDir.exists()) return new ArrayList<>(); - File[] files = logDir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return isMatchLogFileName(name); - } - }); - List list = new ArrayList<>(); - Collections.addAll(list, files); - return list; - } - - private static TagHead processTagAndHead(String tag) { - if (!CONFIG.mTagIsSpace && !CONFIG.isLogHeadSwitch()) { - tag = CONFIG.getGlobalTag(); - } else { - final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); - final int stackIndex = 3 + CONFIG.getStackOffset(); - if (stackIndex >= stackTrace.length) { - StackTraceElement targetElement = stackTrace[3]; - final String fileName = getFileName(targetElement); - if (CONFIG.mTagIsSpace && UtilsBridge.isSpace(tag)) { - int index = fileName.indexOf('.');// Use proguard may not find '.'. - tag = index == -1 ? fileName : fileName.substring(0, index); - } - return new TagHead(tag, null, ": "); - } - StackTraceElement targetElement = stackTrace[stackIndex]; - final String fileName = getFileName(targetElement); - if (CONFIG.mTagIsSpace && UtilsBridge.isSpace(tag)) { - int index = fileName.indexOf('.');// Use proguard may not find '.'. - tag = index == -1 ? fileName : fileName.substring(0, index); - } - if (CONFIG.isLogHeadSwitch()) { - String tName = Thread.currentThread().getName(); - final String head = new Formatter() - .format("%s, %s.%s(%s:%d)", - tName, - targetElement.getClassName(), - targetElement.getMethodName(), - fileName, - targetElement.getLineNumber()) - .toString(); - final String fileHead = " [" + head + "]: "; - if (CONFIG.getStackDeep() <= 1) { - return new TagHead(tag, new String[]{head}, fileHead); - } else { - final String[] consoleHead = - new String[Math.min( - CONFIG.getStackDeep(), - stackTrace.length - stackIndex - )]; - consoleHead[0] = head; - int spaceLen = tName.length() + 2; - String space = new Formatter().format("%" + spaceLen + "s", "").toString(); - for (int i = 1, len = consoleHead.length; i < len; ++i) { - targetElement = stackTrace[i + stackIndex]; - consoleHead[i] = new Formatter() - .format("%s%s.%s(%s:%d)", - space, - targetElement.getClassName(), - targetElement.getMethodName(), - getFileName(targetElement), - targetElement.getLineNumber()) - .toString(); - } - return new TagHead(tag, consoleHead, fileHead); - } - } - } - return new TagHead(tag, null, ": "); - } - - private static String getFileName(final StackTraceElement targetElement) { - String fileName = targetElement.getFileName(); - if (fileName != null) return fileName; - // If name of file is null, should add - // "-keepattributes SourceFile,LineNumberTable" in proguard file. - String className = targetElement.getClassName(); - String[] classNameInfo = className.split("\\."); - if (classNameInfo.length > 0) { - className = classNameInfo[classNameInfo.length - 1]; - } - int index = className.indexOf('$'); - if (index != -1) { - className = className.substring(0, index); - } - return className + ".java"; - } - - private static String processBody(final int type, final Object... contents) { - String body = NULL; - if (contents != null) { - if (contents.length == 1) { - body = formatObject(type, contents[0]); - } else { - StringBuilder sb = new StringBuilder(); - for (int i = 0, len = contents.length; i < len; ++i) { - Object content = contents[i]; - sb.append(ARGS) - .append("[") - .append(i) - .append("]") - .append(" = ") - .append(formatObject(content)) - .append(LINE_SEP); - } - body = sb.toString(); - } - } - return body.length() == 0 ? NOTHING : body; - } - - private static String formatObject(int type, Object object) { - if (object == null) return NULL; - if (type == JSON) return LogFormatter.object2String(object, JSON); - if (type == XML) return LogFormatter.object2String(object, XML); - return formatObject(object); - } - - private static String formatObject(Object object) { - if (object == null) return NULL; - if (!I_FORMATTER_MAP.isEmpty()) { - IFormatter iFormatter = I_FORMATTER_MAP.get(getClassFromObject(object)); - if (iFormatter != null) { - //noinspection unchecked - return iFormatter.format(object); - } - } - return LogFormatter.object2String(object); - } - - private static void print2Console(final int type, - final String tag, - final String[] head, - final String msg) { - if (CONFIG.isSingleTagSwitch()) { - printSingleTagMsg(type, tag, processSingleTagMsg(type, tag, head, msg)); - } else { - printBorder(type, tag, true); - printHead(type, tag, head); - printMsg(type, tag, msg); - printBorder(type, tag, false); - } - } - - private static void printBorder(final int type, final String tag, boolean isTop) { - if (CONFIG.isLogBorderSwitch()) { - print2Console(type, tag, isTop ? TOP_BORDER : BOTTOM_BORDER); - } - } - - private static void printHead(final int type, final String tag, final String[] head) { - if (head != null) { - for (String aHead : head) { - print2Console(type, tag, CONFIG.isLogBorderSwitch() ? LEFT_BORDER + aHead : aHead); - } - if (CONFIG.isLogBorderSwitch()) print2Console(type, tag, MIDDLE_BORDER); - } - } - - private static void printMsg(final int type, final String tag, final String msg) { - int len = msg.length(); - int countOfSub = len / MAX_LEN; - if (countOfSub > 0) { - int index = 0; - for (int i = 0; i < countOfSub; i++) { - printSubMsg(type, tag, msg.substring(index, index + MAX_LEN)); - index += MAX_LEN; - } - if (index != len) { - printSubMsg(type, tag, msg.substring(index, len)); - } - } else { - printSubMsg(type, tag, msg); - } - } - - private static void printSubMsg(final int type, final String tag, final String msg) { - if (!CONFIG.isLogBorderSwitch()) { - print2Console(type, tag, msg); - return; - } - StringBuilder sb = new StringBuilder(); - String[] lines = msg.split(LINE_SEP); - for (String line : lines) { - print2Console(type, tag, LEFT_BORDER + line); - } - } - - private static String processSingleTagMsg(final int type, - final String tag, - final String[] head, - final String msg) { - StringBuilder sb = new StringBuilder(); - if (CONFIG.isLogBorderSwitch()) { - sb.append(PLACEHOLDER).append(LINE_SEP); - sb.append(TOP_BORDER).append(LINE_SEP); - if (head != null) { - for (String aHead : head) { - sb.append(LEFT_BORDER).append(aHead).append(LINE_SEP); - } - sb.append(MIDDLE_BORDER).append(LINE_SEP); - } - for (String line : msg.split(LINE_SEP)) { - sb.append(LEFT_BORDER).append(line).append(LINE_SEP); - } - sb.append(BOTTOM_BORDER); - } else { - if (head != null) { - sb.append(PLACEHOLDER).append(LINE_SEP); - for (String aHead : head) { - sb.append(aHead).append(LINE_SEP); - } - } - sb.append(msg); - } - return sb.toString(); - } - - private static void printSingleTagMsg(final int type, final String tag, final String msg) { - int len = msg.length(); - int countOfSub = CONFIG.isLogBorderSwitch() ? (len - BOTTOM_BORDER.length()) / MAX_LEN : len / MAX_LEN; - if (countOfSub > 0) { - if (CONFIG.isLogBorderSwitch()) { - print2Console(type, tag, msg.substring(0, MAX_LEN) + LINE_SEP + BOTTOM_BORDER); - int index = MAX_LEN; - for (int i = 1; i < countOfSub; i++) { - print2Console(type, tag, PLACEHOLDER + LINE_SEP + TOP_BORDER + LINE_SEP - + LEFT_BORDER + msg.substring(index, index + MAX_LEN) - + LINE_SEP + BOTTOM_BORDER); - index += MAX_LEN; - } - if (index != len - BOTTOM_BORDER.length()) { - print2Console(type, tag, PLACEHOLDER + LINE_SEP + TOP_BORDER + LINE_SEP - + LEFT_BORDER + msg.substring(index, len)); - } - } else { - print2Console(type, tag, msg.substring(0, MAX_LEN)); - int index = MAX_LEN; - for (int i = 1; i < countOfSub; i++) { - print2Console(type, tag, - PLACEHOLDER + LINE_SEP + msg.substring(index, index + MAX_LEN)); - index += MAX_LEN; - } - if (index != len) { - print2Console(type, tag, PLACEHOLDER + LINE_SEP + msg.substring(index, len)); - } - } - } else { - print2Console(type, tag, msg); - } - } - - private static void print2Console(int type, String tag, String msg) { - Log.println(type, tag, msg); - if (CONFIG.mOnConsoleOutputListener != null) { - CONFIG.mOnConsoleOutputListener.onConsoleOutput(type, tag, msg); - } - } - - private static void print2File(final int type, final String tag, final String msg) { - Date d = new Date(); - String format = getSdf().format(d); - String date = format.substring(0, 10); - String currentLogFilePath = getCurrentLogFilePath(d); - if (!createOrExistsFile(currentLogFilePath, date)) { - Log.e("LogUtils", "create " + currentLogFilePath + " failed!"); - return; - } - String time = format.substring(11); - final String content = time + - T[type - V] + - "/" + - tag + - msg + - LINE_SEP; - input2File(currentLogFilePath, content); - } - - private static String getCurrentLogFilePath(Date d) { - String format = getSdf().format(d); - String date = format.substring(0, 10); - return CONFIG.getDir() + CONFIG.getFilePrefix() + "_" - + date + "_" + - CONFIG.getProcessName() + CONFIG.getFileExtension(); - } - - - private static SimpleDateFormat getSdf() { - if (simpleDateFormat == null) { - simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd HH:mm:ss.SSS ", Locale.getDefault()); - } - return simpleDateFormat; - } - - private static boolean createOrExistsFile(final String filePath, final String date) { - File file = new File(filePath); - if (file.exists()) return file.isFile(); - if (!UtilsBridge.createOrExistsDir(file.getParentFile())) return false; - try { - deleteDueLogs(filePath, date); - boolean isCreate = file.createNewFile(); - if (isCreate) { - printDeviceInfo(filePath, date); - } - return isCreate; - } catch (IOException e) { - e.printStackTrace(); - return false; - } - } - - private static void deleteDueLogs(final String filePath, final String date) { - if (CONFIG.getSaveDays() <= 0) return; - File file = new File(filePath); - File parentFile = file.getParentFile(); - File[] files = parentFile.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return isMatchLogFileName(name); - } - }); - if (files == null || files.length <= 0) return; - final SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd", Locale.getDefault()); - try { - long dueMillis = sdf.parse(date).getTime() - CONFIG.getSaveDays() * 86400000L; - for (final File aFile : files) { - String name = aFile.getName(); - int l = name.length(); - String logDay = findDate(name); - if (sdf.parse(logDay).getTime() <= dueMillis) { - EXECUTOR.execute(new Runnable() { - @Override - public void run() { - boolean delete = aFile.delete(); - if (!delete) { - Log.e("LogUtils", "delete " + aFile + " failed!"); - } - } - }); - } - } - } catch (ParseException e) { - e.printStackTrace(); - } - } - - private static boolean isMatchLogFileName(String name) { - return name.matches("^" + CONFIG.getFilePrefix() + "_[0-9]{4}_[0-9]{2}_[0-9]{2}_.*$"); - } - - private static String findDate(String str) { - Pattern pattern = Pattern.compile("[0-9]{4}_[0-9]{2}_[0-9]{2}"); - Matcher matcher = pattern.matcher(str); - if (matcher.find()) { - return matcher.group(); - } - return ""; - } - - private static void printDeviceInfo(final String filePath, final String date) { - CONFIG.mFileHead.addFirst("Date of Log", date); - input2File(filePath, CONFIG.mFileHead.toString()); - } - - private static void input2File(final String filePath, final String input) { - if (CONFIG.mFileWriter == null) { - UtilsBridge.writeFileFromString(filePath, input, true); - } else { - CONFIG.mFileWriter.write(filePath, input); - } - if (CONFIG.mOnFileOutputListener != null) { - CONFIG.mOnFileOutputListener.onFileOutput(filePath, input); - } - } - - public static final class Config { - private String mDefaultDir; // The default storage directory of log. - private String mDir; // The storage directory of log. - private String mFilePrefix = "util";// The file prefix of log. - private String mFileExtension = ".txt";// The file extension of log. - private boolean mLogSwitch = true; // The switch of log. - private boolean mLog2ConsoleSwitch = true; // The logcat's switch of log. - private String mGlobalTag = ""; // The global tag of log. - private boolean mTagIsSpace = true; // The global tag is space. - private boolean mLogHeadSwitch = true; // The head's switch of log. - private boolean mLog2FileSwitch = false; // The file's switch of log. - private boolean mLogBorderSwitch = true; // The border's switch of log. - private boolean mSingleTagSwitch = true; // The single tag of log. - private int mConsoleFilter = V; // The console's filter of log. - private int mFileFilter = V; // The file's filter of log. - private int mStackDeep = 1; // The stack's deep of log. - private int mStackOffset = 0; // The stack's offset of log. - private int mSaveDays = -1; // The save days of log. - private String mProcessName = UtilsBridge.getCurrentProcessName(); - private IFileWriter mFileWriter; - private OnConsoleOutputListener mOnConsoleOutputListener; - private OnFileOutputListener mOnFileOutputListener; - private UtilsBridge.FileHead mFileHead = new UtilsBridge.FileHead("Log"); - - private Config() { - if (UtilsBridge.isSDCardEnableByEnvironment() - && Utils.getApp().getExternalFilesDir(null) != null) - mDefaultDir = Utils.getApp().getExternalFilesDir(null) + FILE_SEP + "log" + FILE_SEP; - else { - mDefaultDir = Utils.getApp().getFilesDir() + FILE_SEP + "log" + FILE_SEP; - } - } - - public final Config setLogSwitch(final boolean logSwitch) { - mLogSwitch = logSwitch; - return this; - } - - public final Config setConsoleSwitch(final boolean consoleSwitch) { - mLog2ConsoleSwitch = consoleSwitch; - return this; - } - - public final Config setGlobalTag(final String tag) { - if (UtilsBridge.isSpace(tag)) { - mGlobalTag = ""; - mTagIsSpace = true; - } else { - mGlobalTag = tag; - mTagIsSpace = false; - } - return this; - } - - public final Config setLogHeadSwitch(final boolean logHeadSwitch) { - mLogHeadSwitch = logHeadSwitch; - return this; - } - - public final Config setLog2FileSwitch(final boolean log2FileSwitch) { - mLog2FileSwitch = log2FileSwitch; - return this; - } - - public final Config setDir(final String dir) { - if (UtilsBridge.isSpace(dir)) { - mDir = null; - } else { - mDir = dir.endsWith(FILE_SEP) ? dir : dir + FILE_SEP; - } - return this; - } - - public final Config setDir(final File dir) { - mDir = dir == null ? null : (dir.getAbsolutePath() + FILE_SEP); - return this; - } - - public final Config setFilePrefix(final String filePrefix) { - if (UtilsBridge.isSpace(filePrefix)) { - mFilePrefix = "util"; - } else { - mFilePrefix = filePrefix; - } - return this; - } - - public final Config setFileExtension(final String fileExtension) { - if (UtilsBridge.isSpace(fileExtension)) { - mFileExtension = ".txt"; - } else { - if (fileExtension.startsWith(".")) { - mFileExtension = fileExtension; - } else { - mFileExtension = "." + fileExtension; - } - } - return this; - } - - public final Config setBorderSwitch(final boolean borderSwitch) { - mLogBorderSwitch = borderSwitch; - return this; - } - - public final Config setSingleTagSwitch(final boolean singleTagSwitch) { - mSingleTagSwitch = singleTagSwitch; - return this; - } - - public final Config setConsoleFilter(@TYPE final int consoleFilter) { - mConsoleFilter = consoleFilter; - return this; - } - - public final Config setFileFilter(@TYPE final int fileFilter) { - mFileFilter = fileFilter; - return this; - } - - public final Config setStackDeep(@IntRange(from = 1) final int stackDeep) { - mStackDeep = stackDeep; - return this; - } - - public final Config setStackOffset(@IntRange(from = 0) final int stackOffset) { - mStackOffset = stackOffset; - return this; - } - - public final Config setSaveDays(@IntRange(from = 1) final int saveDays) { - mSaveDays = saveDays; - return this; - } - - public final Config addFormatter(final IFormatter iFormatter) { - if (iFormatter != null) { - I_FORMATTER_MAP.put(getTypeClassFromParadigm(iFormatter), iFormatter); - } - return this; - } - - public final Config setFileWriter(final IFileWriter fileWriter) { - mFileWriter = fileWriter; - return this; - } - - public final Config setOnConsoleOutputListener(final OnConsoleOutputListener listener) { - mOnConsoleOutputListener = listener; - return this; - } - - public final Config setOnFileOutputListener(final OnFileOutputListener listener) { - mOnFileOutputListener = listener; - return this; - } - - public final Config addFileExtraHead(final Map fileExtraHead) { - mFileHead.append(fileExtraHead); - return this; - } - - public final Config addFileExtraHead(final String key, final String value) { - mFileHead.append(key, value); - return this; - } - - public final String getProcessName() { - if (mProcessName == null) return ""; - return mProcessName.replace(":", "_"); - } - - public final String getDefaultDir() { - return mDefaultDir; - } - - public final String getDir() { - return mDir == null ? mDefaultDir : mDir; - } - - public final String getFilePrefix() { - return mFilePrefix; - } - - public final String getFileExtension() { - return mFileExtension; - } - - public final boolean isLogSwitch() { - return mLogSwitch; - } - - public final boolean isLog2ConsoleSwitch() { - return mLog2ConsoleSwitch; - } - - public final String getGlobalTag() { - if (UtilsBridge.isSpace(mGlobalTag)) return ""; - return mGlobalTag; - } - - public final boolean isLogHeadSwitch() { - return mLogHeadSwitch; - } - - public final boolean isLog2FileSwitch() { - return mLog2FileSwitch; - } - - public final boolean isLogBorderSwitch() { - return mLogBorderSwitch; - } - - public final boolean isSingleTagSwitch() { - return mSingleTagSwitch; - } - - public final char getConsoleFilter() { - return T[mConsoleFilter - V]; - } - - public final char getFileFilter() { - return T[mFileFilter - V]; - } - - public final int getStackDeep() { - return mStackDeep; - } - - public final int getStackOffset() { - return mStackOffset; - } - - public final int getSaveDays() { - return mSaveDays; - } - - public final boolean haveSetOnConsoleOutputListener() { - return mOnConsoleOutputListener != null; - } - - public final boolean haveSetOnFileOutputListener() { - return mOnFileOutputListener != null; - } - - @Override - public String toString() { - return "process: " + getProcessName() - + LINE_SEP + "logSwitch: " + isLogSwitch() - + LINE_SEP + "consoleSwitch: " + isLog2ConsoleSwitch() - + LINE_SEP + "tag: " + (getGlobalTag().equals("") ? "null" : getGlobalTag()) - + LINE_SEP + "headSwitch: " + isLogHeadSwitch() - + LINE_SEP + "fileSwitch: " + isLog2FileSwitch() - + LINE_SEP + "dir: " + getDir() - + LINE_SEP + "filePrefix: " + getFilePrefix() - + LINE_SEP + "borderSwitch: " + isLogBorderSwitch() - + LINE_SEP + "singleTagSwitch: " + isSingleTagSwitch() - + LINE_SEP + "consoleFilter: " + getConsoleFilter() - + LINE_SEP + "fileFilter: " + getFileFilter() - + LINE_SEP + "stackDeep: " + getStackDeep() - + LINE_SEP + "stackOffset: " + getStackOffset() - + LINE_SEP + "saveDays: " + getSaveDays() - + LINE_SEP + "formatter: " + I_FORMATTER_MAP - + LINE_SEP + "fileWriter: " + mFileWriter - + LINE_SEP + "onConsoleOutputListener: " + mOnConsoleOutputListener - + LINE_SEP + "onFileOutputListener: " + mOnFileOutputListener - + LINE_SEP + "fileExtraHeader: " + mFileHead.getAppended(); - } - } - - public abstract static class IFormatter { - public abstract String format(T t); - } - - public interface IFileWriter { - void write(String file, String content); - } - - public interface OnConsoleOutputListener { - void onConsoleOutput(@TYPE int type, String tag, String content); - } - - public interface OnFileOutputListener { - void onFileOutput(String filePath, String content); - } - - private final static class TagHead { - String tag; - String[] consoleHead; - String fileHead; - - TagHead(String tag, String[] consoleHead, String fileHead) { - this.tag = tag; - this.consoleHead = consoleHead; - this.fileHead = fileHead; - } - } - - private final static class LogFormatter { - - static String object2String(Object object) { - return object2String(object, -1); - } - - static String object2String(Object object, int type) { - if (object.getClass().isArray()) return array2String(object); - if (object instanceof Throwable) - return UtilsBridge.getFullStackTrace((Throwable) object); - if (object instanceof Bundle) return bundle2String((Bundle) object); - if (object instanceof Intent) return intent2String((Intent) object); - if (type == JSON) { - return object2Json(object); - } else if (type == XML) { - return formatXml(object.toString()); - } - return object.toString(); - } - - private static String bundle2String(Bundle bundle) { - Iterator iterator = bundle.keySet().iterator(); - if (!iterator.hasNext()) { - return "Bundle {}"; - } - StringBuilder sb = new StringBuilder(128); - sb.append("Bundle { "); - for (; ; ) { - String key = iterator.next(); - Object value = bundle.get(key); - sb.append(key).append('='); - if (value instanceof Bundle) { - sb.append(value == bundle ? "(this Bundle)" : bundle2String((Bundle) value)); - } else { - sb.append(formatObject(value)); - } - if (!iterator.hasNext()) return sb.append(" }").toString(); - sb.append(',').append(' '); - } - } - - private static String intent2String(Intent intent) { - StringBuilder sb = new StringBuilder(128); - sb.append("Intent { "); - boolean first = true; - String mAction = intent.getAction(); - if (mAction != null) { - sb.append("act=").append(mAction); - first = false; - } - Set mCategories = intent.getCategories(); - if (mCategories != null) { - if (!first) { - sb.append(' '); - } - first = false; - sb.append("cat=["); - boolean firstCategory = true; - for (String c : mCategories) { - if (!firstCategory) { - sb.append(','); - } - sb.append(c); - firstCategory = false; - } - sb.append("]"); - } - Uri mData = intent.getData(); - if (mData != null) { - if (!first) { - sb.append(' '); - } - first = false; - sb.append("dat=").append(mData); - } - String mType = intent.getType(); - if (mType != null) { - if (!first) { - sb.append(' '); - } - first = false; - sb.append("typ=").append(mType); - } - int mFlags = intent.getFlags(); - if (mFlags != 0) { - if (!first) { - sb.append(' '); - } - first = false; - sb.append("flg=0x").append(Integer.toHexString(mFlags)); - } - String mPackage = intent.getPackage(); - if (mPackage != null) { - if (!first) { - sb.append(' '); - } - first = false; - sb.append("pkg=").append(mPackage); - } - ComponentName mComponent = intent.getComponent(); - if (mComponent != null) { - if (!first) { - sb.append(' '); - } - first = false; - sb.append("cmp=").append(mComponent.flattenToShortString()); - } - Rect mSourceBounds = intent.getSourceBounds(); - if (mSourceBounds != null) { - if (!first) { - sb.append(' '); - } - first = false; - sb.append("bnds=").append(mSourceBounds.toShortString()); - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - ClipData mClipData = intent.getClipData(); - if (mClipData != null) { - if (!first) { - sb.append(' '); - } - first = false; - clipData2String(mClipData, sb); - } - } - Bundle mExtras = intent.getExtras(); - if (mExtras != null) { - if (!first) { - sb.append(' '); - } - first = false; - sb.append("extras={"); - sb.append(bundle2String(mExtras)); - sb.append('}'); - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { - Intent mSelector = intent.getSelector(); - if (mSelector != null) { - if (!first) { - sb.append(' '); - } - first = false; - sb.append("sel={"); - sb.append(mSelector == intent ? "(this Intent)" : intent2String(mSelector)); - sb.append("}"); - } - } - sb.append(" }"); - return sb.toString(); - } - - @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) - private static void clipData2String(ClipData clipData, StringBuilder sb) { - ClipData.Item item = clipData.getItemAt(0); - if (item == null) { - sb.append("ClipData.Item {}"); - return; - } - sb.append("ClipData.Item { "); - String mHtmlText = item.getHtmlText(); - if (mHtmlText != null) { - sb.append("H:"); - sb.append(mHtmlText); - sb.append("}"); - return; - } - CharSequence mText = item.getText(); - if (mText != null) { - sb.append("T:"); - sb.append(mText); - sb.append("}"); - return; - } - Uri uri = item.getUri(); - if (uri != null) { - sb.append("U:").append(uri); - sb.append("}"); - return; - } - Intent intent = item.getIntent(); - if (intent != null) { - sb.append("I:"); - sb.append(intent2String(intent)); - sb.append("}"); - return; - } - sb.append("NULL"); - sb.append("}"); - } - - private static String object2Json(Object object) { - if (object instanceof CharSequence) { - return UtilsBridge.formatJson(object.toString()); - } - try { - return UtilsBridge.getGson4LogUtils().toJson(object); - } catch (Throwable t) { - return object.toString(); - } - } - - private static String formatJson(String json) { - try { - for (int i = 0, len = json.length(); i < len; i++) { - char c = json.charAt(i); - if (c == '{') { - return new JSONObject(json).toString(2); - } else if (c == '[') { - return new JSONArray(json).toString(2); - } else if (!Character.isWhitespace(c)) { - return json; - } - } - } catch (JSONException e) { - e.printStackTrace(); - } - return json; - } - - private static String formatXml(String xml) { - try { - Source xmlInput = new StreamSource(new StringReader(xml)); - StreamResult xmlOutput = new StreamResult(new StringWriter()); - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); - transformer.transform(xmlInput, xmlOutput); - xml = xmlOutput.getWriter().toString().replaceFirst(">", ">" + LINE_SEP); - } catch (Exception e) { - e.printStackTrace(); - } - return xml; - } - - private static String array2String(Object object) { - if (object instanceof Object[]) { - return Arrays.deepToString((Object[]) object); - } else if (object instanceof boolean[]) { - return Arrays.toString((boolean[]) object); - } else if (object instanceof byte[]) { - return Arrays.toString((byte[]) object); - } else if (object instanceof char[]) { - return Arrays.toString((char[]) object); - } else if (object instanceof double[]) { - return Arrays.toString((double[]) object); - } else if (object instanceof float[]) { - return Arrays.toString((float[]) object); - } else if (object instanceof int[]) { - return Arrays.toString((int[]) object); - } else if (object instanceof long[]) { - return Arrays.toString((long[]) object); - } else if (object instanceof short[]) { - return Arrays.toString((short[]) object); - } - throw new IllegalArgumentException("Array has incompatible type: " + object.getClass()); - } - } - - private static Class getTypeClassFromParadigm(final IFormatter formatter) { - Type[] genericInterfaces = formatter.getClass().getGenericInterfaces(); - Type type; - if (genericInterfaces.length == 1) { - type = genericInterfaces[0]; - } else { - type = formatter.getClass().getGenericSuperclass(); - } - type = ((ParameterizedType) type).getActualTypeArguments()[0]; - while (type instanceof ParameterizedType) { - type = ((ParameterizedType) type).getRawType(); - } - String className = type.toString(); - if (className.startsWith("class ")) { - className = className.substring(6); - } else if (className.startsWith("interface ")) { - className = className.substring(10); - } - try { - return Class.forName(className); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - return null; - } - - private static Class getClassFromObject(final Object obj) { - Class objClass = obj.getClass(); - if (objClass.isAnonymousClass() || objClass.isSynthetic()) { - Type[] genericInterfaces = objClass.getGenericInterfaces(); - String className; - if (genericInterfaces.length == 1) {// interface - Type type = genericInterfaces[0]; - while (type instanceof ParameterizedType) { - type = ((ParameterizedType) type).getRawType(); - } - className = type.toString(); - } else {// abstract class or lambda - Type type = objClass.getGenericSuperclass(); - while (type instanceof ParameterizedType) { - type = ((ParameterizedType) type).getRawType(); - } - className = type.toString(); - } - - if (className.startsWith("class ")) { - className = className.substring(6); - } else if (className.startsWith("interface ")) { - className = className.substring(10); - } - try { - return Class.forName(className); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - return objClass; - } -} diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/MatcherUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/MatcherUtils.java index 1bbb89a98c..bb674f1b95 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/MatcherUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/MatcherUtils.java @@ -104,7 +104,7 @@ public class MatcherUtils { * @return */ public static boolean isMatches( String regex, String input) { - return input == null ? false : Pattern.compile(regex).matcher(input).find(); + return input != null && Pattern.compile(regex).matcher(input).find(); } /** @@ -115,7 +115,7 @@ public class MatcherUtils { * @return */ public static boolean isMatchesIgnoreCase( String regex, String input) { - return input == null ? false : Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(input).find(); + return input != null && Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(input).find(); } /** @@ -274,15 +274,13 @@ public class MatcherUtils { */ public static boolean isCJK(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); - if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS // CJK统一汉字 \\u4E00-\\u9fAF + // 半形及全形字符 \\uFF00-\\uFFEF + return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS // CJK统一汉字 \\u4E00-\\u9fAF || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A // CJK统一汉字扩展-A \\u3400-\\u4dBF || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS // CJK兼容汉字 \\uF900-\\uFAFF || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION // CJK符号和标点 \\u3000-\\u303F || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION // 广义标点 \\u2000-\\u206F - || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { // 半形及全形字符 \\uFF00-\\uFFEF - return true; - } - return false; + || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS; } /** @@ -358,6 +356,9 @@ public class MatcherUtils { * @return */ public static boolean isFetionPassword( String input) { + if(input == null){ + return false; + } // 密码必须含有字母和数字,符号可选,但是必须符合Punct标准,否则返回false // 首先判断是否含有无效字符,含有,则返回false if (isIncludeInvalidChar(input)) { @@ -374,11 +375,7 @@ public class MatcherUtils { if (isMatches("[0-9]{1,15}", input)) { tmpValue++; } - if (tmpValue >= 2) { - return true; - } else { - return false; - } + return tmpValue >= 2; } /** @@ -390,9 +387,6 @@ public class MatcherUtils { public static boolean isNumeric( String str) { Pattern pattern = Pattern.compile("[0-9]+"); Matcher isNum = pattern.matcher(str); - if (!isNum.matches()) { - return false; - } - return true; + return isNum.matches(); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/NumberUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/NumberUtils.java index eb536d89e1..fb6e446941 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/NumberUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/NumberUtils.java @@ -20,6 +20,11 @@ public final class NumberUtils { protected DecimalFormat initialValue() { return (DecimalFormat) NumberFormat.getInstance(); } + + @Override + public void remove() { + super.remove(); + } }; public static DecimalFormat getSafeDecimalFormat() { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/PhoneUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/PhoneUtils.java index 55649cef72..a4da2a7ba2 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/PhoneUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/PhoneUtils.java @@ -120,7 +120,7 @@ public final class PhoneUtils { } else { return getMinOne(tm.getMeid(0), tm.getMeid(1)); } - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + } else { String ids = getSystemPropertyByReflect(isImei ? "ril.gsm.imei" : "ril.cdma.meid"); if (!TextUtils.isEmpty(ids)) { String[] idArr = ids.split(","); @@ -138,11 +138,7 @@ public final class PhoneUtils { id1 = (String) method.invoke(tm, isImei ? TelephonyManager.PHONE_TYPE_GSM : TelephonyManager.PHONE_TYPE_CDMA); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } if (isImei) { @@ -161,19 +157,7 @@ public final class PhoneUtils { } } return getMinOne(id0, id1); - } else { - String deviceId = tm.getDeviceId(); - if (isImei) { - if (deviceId != null && deviceId.length() >= 15) { - return deviceId; - } - } else { - if (deviceId != null && deviceId.length() == 14) { - return deviceId; - } - } } - return ""; } private static String getMinOne(String s0, String s1) { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ProcessUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ProcessUtils.java index 5419e2a828..913c2cd0e5 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ProcessUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ProcessUtils.java @@ -58,7 +58,7 @@ public final class ProcessUtils { public static String getForegroundProcessName() { ActivityManager am = (ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE); - //noinspection ConstantConditions + //noinspection Constant Conditions List pInfo = am.getRunningAppProcesses(); if (pInfo != null && pInfo.size() > 0) { for (ActivityManager.RunningAppProcessInfo aInfo : pInfo) { @@ -68,57 +68,55 @@ public final class ProcessUtils { } } } - if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) { - PackageManager pm = Utils.getApp().getPackageManager(); - Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); - List list = - pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); - Log.i("ProcessUtils", list.toString()); - if (list.size() <= 0) { + PackageManager pm = Utils.getApp().getPackageManager(); + Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); + List list = + pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); + Log.i("ProcessUtils", list.toString()); + if (list.size() <= 0) { + Log.i("ProcessUtils", + "getForegroundProcessName: noun of access to usage information."); + return ""; + } + try {// Access to usage information. + ApplicationInfo info = + pm.getApplicationInfo(Utils.getApp().getPackageName(), 0); + AppOpsManager aom = + (AppOpsManager) Utils.getApp().getSystemService(Context.APP_OPS_SERVICE); + if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, + info.uid, + info.packageName) != AppOpsManager.MODE_ALLOWED) { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + Utils.getApp().startActivity(intent); + } + if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, + info.uid, + info.packageName) != AppOpsManager.MODE_ALLOWED) { Log.i("ProcessUtils", - "getForegroundProcessName: noun of access to usage information."); + "getForegroundProcessName: refuse to device usage stats."); return ""; } - try {// Access to usage information. - ApplicationInfo info = - pm.getApplicationInfo(Utils.getApp().getPackageName(), 0); - AppOpsManager aom = - (AppOpsManager) Utils.getApp().getSystemService(Context.APP_OPS_SERVICE); - if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, - info.uid, - info.packageName) != AppOpsManager.MODE_ALLOWED) { - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - Utils.getApp().startActivity(intent); - } - if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, - info.uid, - info.packageName) != AppOpsManager.MODE_ALLOWED) { - Log.i("ProcessUtils", - "getForegroundProcessName: refuse to device usage stats."); - return ""; - } - UsageStatsManager usageStatsManager = (UsageStatsManager) Utils.getApp() - .getSystemService(Context.USAGE_STATS_SERVICE); - List usageStatsList = null; - if (usageStatsManager != null) { - long endTime = System.currentTimeMillis(); - long beginTime = endTime - 86400000 * 7; - usageStatsList = usageStatsManager - .queryUsageStats(UsageStatsManager.INTERVAL_BEST, - beginTime, endTime); - } - if (usageStatsList == null || usageStatsList.isEmpty()) return ""; - UsageStats recentStats = null; - for (UsageStats usageStats : usageStatsList) { - if (recentStats == null - || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) { - recentStats = usageStats; - } - } - return recentStats == null ? null : recentStats.getPackageName(); - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); + UsageStatsManager usageStatsManager = (UsageStatsManager) Utils.getApp() + .getSystemService(Context.USAGE_STATS_SERVICE); + List usageStatsList = null; + if (usageStatsManager != null) { + long endTime = System.currentTimeMillis(); + long beginTime = endTime - 86400000 * 7; + usageStatsList = usageStatsManager + .queryUsageStats(UsageStatsManager.INTERVAL_BEST, + beginTime, endTime); } + if (usageStatsList == null || usageStatsList.isEmpty()) return ""; + UsageStats recentStats = null; + for (UsageStats usageStats : usageStatsList) { + if (recentStats == null + || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) { + recentStats = usageStats; + } + } + return recentStats == null ? null : recentStats.getPackageName(); + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); } return ""; } @@ -223,9 +221,8 @@ public final class ProcessUtils { } private static String getCurrentProcessNameByFile() { - try { - File file = new File("/proc/" + Process.myPid() + "/" + "cmdline"); - BufferedReader mBufferedReader = new BufferedReader(new FileReader(file)); + File file = new File("/proc/" + Process.myPid() + "/" + "cmdline"); + try(BufferedReader mBufferedReader = new BufferedReader(new FileReader(file))) { String processName = mBufferedReader.readLine().trim(); mBufferedReader.close(); return processName; @@ -301,7 +298,7 @@ public final class ProcessUtils { } public static String getPackageName() { - String packageName = null; + String packageName; BufferedReader reader = null; try { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ReflectUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ReflectUtils.java index edffee1272..47ab01c38e 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ReflectUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ReflectUtils.java @@ -158,23 +158,20 @@ public final class ReflectUtils { } private void sortConstructors(List> list) { - Collections.sort(list, new Comparator>() { - @Override - public int compare(Constructor o1, Constructor o2) { - Class[] types1 = o1.getParameterTypes(); - Class[] types2 = o2.getParameterTypes(); - int len = types1.length; - for (int i = 0; i < len; i++) { - if (!types1[i].equals(types2[i])) { - if (wrapper(types1[i]).isAssignableFrom(wrapper(types2[i]))) { - return 1; - } else { - return -1; - } + Collections.sort(list, (o1, o2) -> { + Class[] types1 = o1.getParameterTypes(); + Class[] types2 = o2.getParameterTypes(); + int len = types1.length; + for (int i = 0; i < len; i++) { + if (!types1[i].equals(types2[i])) { + if (wrapper(types1[i]).isAssignableFrom(wrapper(types2[i]))) { + return 1; + } else { + return -1; } } - return 0; } + return 0; }); } @@ -363,23 +360,20 @@ public final class ReflectUtils { } private void sortMethods(final List methods) { - Collections.sort(methods, new Comparator() { - @Override - public int compare(Method o1, Method o2) { - Class[] types1 = o1.getParameterTypes(); - Class[] types2 = o2.getParameterTypes(); - int len = types1.length; - for (int i = 0; i < len; i++) { - if (!types1[i].equals(types2[i])) { - if (wrapper(types1[i]).isAssignableFrom(wrapper(types2[i]))) { - return 1; - } else { - return -1; - } + Collections.sort(methods, (o1, o2) -> { + Class[] types1 = o1.getParameterTypes(); + Class[] types2 = o2.getParameterTypes(); + int len = types1.length; + for (int i = 0; i < len; i++) { + if (!types1[i].equals(types2[i])) { + if (wrapper(types1[i]).isAssignableFrom(wrapper(types2[i]))) { + return 1; + } else { + return -1; } } - return 0; } + return 0; }); } @@ -432,29 +426,25 @@ public final class ReflectUtils { @SuppressWarnings("unchecked") public

P proxy(final Class

proxyType) { final boolean isMap = (object instanceof Map); - final InvocationHandler handler = new InvocationHandler() { - @Override - @SuppressWarnings("null") - public Object invoke(Object proxy, Method method, Object[] args) { - String name = method.getName(); - try { - return reflect(object).method(name, args).get(); - } catch (ReflectException e) { - if (isMap) { - Map map = (Map) object; - int length = (args == null ? 0 : args.length); + final InvocationHandler handler = (proxy, method, args) -> { + String name = method.getName(); + try { + return reflect(object).method(name, args).get(); + } catch (ReflectException e) { + if (isMap) { + Map map = (Map) object; + int length = (args == null ? 0 : args.length); - if (length == 0 && name.startsWith("get")) { - return map.get(property(name.substring(3))); - } else if (length == 0 && name.startsWith("is")) { - return map.get(property(name.substring(2))); - } else if (length == 1 && name.startsWith("set")) { - map.put(property(name.substring(3)), args[0]); - return null; - } + if (length == 0 && name.startsWith("get")) { + return map.get(property(name.substring(3))); + } else if (length == 0 && name.startsWith("is")) { + return map.get(property(name.substring(2))); + } else if (length == 1 && name.startsWith("set")) { + map.put(property(name.substring(3)), args[0]); + return null; } - throw e; } + throw e; } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/RomUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/RomUtils.java index 581c7d26af..5753635382 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/RomUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/RomUtils.java @@ -393,7 +393,6 @@ public final class RomUtils { } private static String getSystemPropertyByShell(final String propName) { - String line; BufferedReader input = null; try { Process p = Runtime.getRuntime().exec("getprop " + propName); @@ -414,11 +413,9 @@ public final class RomUtils { } private static String getSystemPropertyByStream(final String key) { - try { + try( FileInputStream is = new FileInputStream( + new File(Environment.getRootDirectory(), "build.prop"))) { Properties prop = new Properties(); - FileInputStream is = new FileInputStream( - new File(Environment.getRootDirectory(), "build.prop") - ); prop.load(is); return prop.getProperty(key, ""); } catch (Exception ignore) {/**/} diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ShadowUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ShadowUtils.java index 8f13023d0a..f4e8094950 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ShadowUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ShadowUtils.java @@ -182,10 +182,10 @@ public class ShadowUtils { private float mShadowHorizScale = 1f; private float mShadowBottomScale = 1f; - private Paint mCornerShadowPaint; - private Paint mEdgeShadowPaint; + private final Paint mCornerShadowPaint; + private final Paint mEdgeShadowPaint; - private RectF mContentBounds; + private final RectF mContentBounds; private float mCornerRadius; @@ -210,7 +210,7 @@ public class ShadowUtils { private float mRotation; - private boolean isCircle; + private final boolean isCircle; public ShadowDrawable(Drawable content, float radius, float shadowSize, float maxShadowSize, int shadowColor, boolean isCircle) { @@ -494,7 +494,7 @@ public class ShadowUtils { // We could have different top-bottom offsets to avoid extra gap above but in that case // center aligning Views inside the CardView would be problematic. if (isCircle) { - mCornerRadius = bounds.width() / 2; + mCornerRadius = bounds.width() / 2.0f; } final float verticalOffset = mRawMaxShadowSize * mShadowMultiplier; mContentBounds.set(bounds.left + mRawMaxShadowSize, bounds.top + verticalOffset, @@ -679,7 +679,7 @@ public class ShadowUtils { public void setWrappedDrawable(Drawable drawable) { if (this.mDrawable != null) { - this.mDrawable.setCallback((Callback) null); + this.mDrawable.setCallback(null); } this.mDrawable = drawable; diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ShellUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ShellUtils.java index e32b943363..6cb6015e9d 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ShellUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ShellUtils.java @@ -6,6 +6,7 @@ import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.List; /** @@ -308,10 +309,10 @@ public final class ShellUtils { successMsg = new StringBuilder(); errorMsg = new StringBuilder(); successResult = new BufferedReader( - new InputStreamReader(process.getInputStream(), "UTF-8") + new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8) ); errorResult = new BufferedReader( - new InputStreamReader(process.getErrorStream(), "UTF-8") + new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8) ); String line; if ((line = successResult.readLine()) != null) { @@ -334,17 +335,9 @@ public final class ShellUtils { if (os != null) { os.close(); } - } catch (IOException e) { - e.printStackTrace(); - } - try { if (successResult != null) { successResult.close(); } - } catch (IOException e) { - e.printStackTrace(); - } - try { if (errorResult != null) { errorResult.close(); } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SoundPoolUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SoundPoolUtils.java index a1a05b03af..4f6134dce5 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SoundPoolUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SoundPoolUtils.java @@ -1,5 +1,6 @@ package com.mogo.eagle.core.utilcode.util; +import android.annotation.SuppressLint; import android.media.*; import android.content.*; import android.os.*; @@ -21,20 +22,15 @@ public class SoundPoolUtils { private int resId; private Context mContext; - private volatile static SoundPoolUtils INSTANCE; - + private SoundPoolUtils(){} public static SoundPoolUtils getSoundPool(){ - if (INSTANCE == null){ - synchronized (SoundPoolUtils.class){ - if (INSTANCE == null){ - INSTANCE = new SoundPoolUtils(); - } - } - } - return INSTANCE; + return Holder.INSTANCE; + } + + private static final class Holder{ + @SuppressLint("StaticFieldLeak") + private static final SoundPoolUtils INSTANCE = new SoundPoolUtils(); } - - public SoundPoolUtils(){} //播放资源文件 public void playSoundWithRedId(Context context,int resId){ @@ -63,30 +59,20 @@ public class SoundPoolUtils { if (mSoundPool == null){ // For Android SDK >= 21 - if (Build.VERSION.SDK_INT >= 21 ) { - AudioAttributes audioAttrib = new AudioAttributes.Builder() - .setUsage(AudioAttributes.USAGE_GAME) - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .build(); + AudioAttributes audioAttrib = new AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_GAME) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .build(); - SoundPool.Builder builder= new SoundPool.Builder(); - builder.setAudioAttributes(audioAttrib).setMaxStreams(MAX_STREAMS); + SoundPool.Builder builder= new SoundPool.Builder(); + builder.setAudioAttributes(audioAttrib).setMaxStreams(MAX_STREAMS); - this.mSoundPool = builder.build(); - } else {// for Android SDK < 21 - // SoundPool(int maxStreams, int streamType, int srcQuality) - this.mSoundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0); - } + this.mSoundPool = builder.build(); } // When Sound Pool load complete. - this.mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { - @Override - public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { - playSound(); - } - }); + this.mSoundPool.setOnLoadCompleteListener((soundPool, sampleId, status) -> playSound()); //load res this.mSoundId =this.mSoundPool.load(this.mContext,this.resId,1); @@ -108,10 +94,10 @@ public class SoundPoolUtils { //play the sound res private void playSound(){ - float leftVolumn = volume; - float rightVolumn = volume; + float leftVolume = volume; + float rightVolume = volume; // Play sound of gunfire. Returns the ID of the new stream. - int streamId = this.mSoundPool.play(this.mSoundId,leftVolumn, rightVolumn, 1, 0, 1f); + int streamId = this.mSoundPool.play(this.mSoundId,leftVolume, rightVolume, 1, 0, 1f); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SpanUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SpanUtils.java index 6bed3d892c..35ba5f0437 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SpanUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SpanUtils.java @@ -139,7 +139,7 @@ public final class SpanUtils { private int spaceSize; private int spaceColor; - private SerializableSpannableStringBuilder mBuilder; + private final SerializableSpannableStringBuilder mBuilder; private boolean isCreated; private int mType; @@ -1031,7 +1031,7 @@ public final class SpanUtils { // } // } - canvas.drawText(text.toString(), x, y - ((y + fm.descent + y + fm.ascent) / 2 - (bottom + top) / 2), paint); + canvas.drawText(text.toString(), x, y - ((y + fm.descent + y + fm.ascent) / 2.0f - (bottom + top) / 2.0f), paint); } } @@ -1189,7 +1189,7 @@ public final class SpanUtils { final boolean first, final Layout l) { if (((Spanned) text).getSpanStart(this) == start) { Paint.Style style = p.getStyle(); - int oldColor = 0; + int oldColor; oldColor = p.getColor(); p.setColor(color); p.setStyle(Paint.Style.FILL); @@ -1200,11 +1200,11 @@ public final class SpanUtils { sBulletPath.addCircle(0.0f, 0.0f, radius, Path.Direction.CW); } c.save(); - c.translate(x + dir * radius, (top + bottom) / 2.0f); + c.translate((float)(x + dir * radius), (top + bottom) / 2.0f); c.drawPath(sBulletPath, p); c.restore(); } else { - c.drawCircle(x + dir * radius, (top + bottom) / 2.0f, radius, p); + c.drawCircle((float)(x + dir * radius), (top + bottom) / 2.0f, radius, p); } p.setColor(oldColor); p.setStyle(style); @@ -1249,9 +1249,6 @@ public final class SpanUtils { if ((fake & Typeface.ITALIC) != 0) { paint.setTextSkewX(-0.25f); } - - paint.getShader(); - paint.setTypeface(tf); } } @@ -1311,9 +1308,11 @@ public final class SpanUtils { } else { try { drawable = ContextCompat.getDrawable(Utils.getApp(), mResourceId); - drawable.setBounds( - 0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight() - ); + if(drawable != null){ + drawable.setBounds( + 0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight() + ); + } } catch (Exception e) { Log.e("sms", "Unable to find resource: " + mResourceId); } @@ -1358,14 +1357,12 @@ public final class SpanUtils { int lineHeight = fm.bottom - fm.top; if (lineHeight < rect.height()) { if (mVerticalAlignment == ALIGN_TOP) { - fm.top = fm.top; fm.bottom = rect.height() + fm.top; } else if (mVerticalAlignment == ALIGN_CENTER) { fm.top = -rect.height() / 2 - lineHeight / 4; fm.bottom = rect.height() / 2 - lineHeight / 4; } else { fm.top = -rect.height() + fm.bottom; - fm.bottom = fm.bottom; } fm.ascent = fm.top; fm.descent = fm.bottom; @@ -1389,7 +1386,7 @@ public final class SpanUtils { if (mVerticalAlignment == ALIGN_TOP) { transY = top; } else if (mVerticalAlignment == ALIGN_CENTER) { - transY = (bottom + top - rect.height()) / 2; + transY = (bottom + top - rect.height()) / 2.0f; } else if (mVerticalAlignment == ALIGN_BASELINE) { transY = y - rect.height(); } else { @@ -1420,7 +1417,7 @@ public final class SpanUtils { } static class ShaderSpan extends CharacterStyle implements UpdateAppearance { - private Shader mShader; + private final Shader mShader; private ShaderSpan(final Shader shader) { this.mShader = shader; @@ -1433,9 +1430,10 @@ public final class SpanUtils { } static class ShadowSpan extends CharacterStyle implements UpdateAppearance { - private float radius; - private float dx, dy; - private int shadowColor; + private final float radius; + private final float dx; + private final float dy; + private final int shadowColor; private ShadowSpan(final float radius, final float dx, diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SystemPropertiesUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SystemPropertiesUtils.java index 04e0563543..07bda7a10d 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SystemPropertiesUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SystemPropertiesUtils.java @@ -11,16 +11,15 @@ public final class SystemPropertiesUtils { public static String getProperty(String key, String defaultValue) { String value = defaultValue; - try { Class c = Class.forName(CLASS_NAME); Method get = c.getMethod("get", String.class, String.class); value = (String) (get.invoke(c, key, defaultValue)); + return value; } catch (Exception e) { e.printStackTrace(); - } finally { - return value; } + return value; } public static void setProperty(String key, String value) { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ThreadUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ThreadUtils.java index 171817dd7d..184d014669 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ThreadUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ThreadUtils.java @@ -1068,7 +1068,7 @@ public final class ThreadUtils { private final AtomicInteger mSubmittedCount = new AtomicInteger(); - private LinkedBlockingQueue4Util mWorkQueue; + private final LinkedBlockingQueue4Util mWorkQueue; ThreadPoolExecutor4Util(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, @@ -1376,8 +1376,8 @@ public final class ThreadUtils { public static class SyncValue { - private CountDownLatch mLatch = new CountDownLatch(1); - private AtomicBoolean mFlag = new AtomicBoolean(); + private final CountDownLatch mLatch = new CountDownLatch(1); + private final AtomicBoolean mFlag = new AtomicBoolean(); private T mValue; public void setValue(T value) { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeTransformUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeTransformUtils.java index c7f2ce6ced..5c46a7945b 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeTransformUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeTransformUtils.java @@ -19,11 +19,14 @@ public final class TimeTransformUtils { int hours = totalSeconds / 3600; StringBuilder stringBuilder = new StringBuilder(); Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault()); + String formatStr; if (hours > 0) { - return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); + formatStr = mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); } else { - return mFormatter.format("%02d:%02d", minutes, seconds).toString(); + formatStr = mFormatter.format("%02d:%02d", minutes, seconds).toString(); } + mFormatter.close(); + return formatStr; } public static String stringForTimeWithHours(int timeMs) { @@ -36,7 +39,9 @@ public final class TimeTransformUtils { int hours = totalSeconds / 3600; StringBuilder stringBuilder = new StringBuilder(); Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault()); - return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); + String formatStr = mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); + mFormatter.close(); + return formatStr; } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeUtils.java index f8fd01abba..2ad587de61 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeUtils.java @@ -36,6 +36,11 @@ public final class TimeUtils { protected Map initialValue() { return new HashMap<>(); } + + @Override + public void remove() { + super.remove(); + } }; private static SimpleDateFormat getDefaultFormat() { diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/UtilsActivityLifecycleImpl.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/UtilsActivityLifecycleImpl.java index 7ec8d03d0b..37f6a33d56 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/UtilsActivityLifecycleImpl.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/UtilsActivityLifecycleImpl.java @@ -118,23 +118,13 @@ final class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleC void removeActivityLifecycleCallbacks(final Activity activity) { if (activity == null) return; - UtilsBridge.runOnUiThread(new Runnable() { - @Override - public void run() { - mActivityLifecycleCallbacksMap.remove(activity); - } - }); + UtilsBridge.runOnUiThread(() -> mActivityLifecycleCallbacksMap.remove(activity)); } void removeActivityLifecycleCallbacks(final Activity activity, final Utils.ActivityLifecycleCallbacks callbacks) { if (activity == null || callbacks == null) return; - UtilsBridge.runOnUiThread(new Runnable() { - @Override - public void run() { - removeActivityLifecycleCallbacksInner(activity, callbacks); - } - }); + UtilsBridge.runOnUiThread(() -> removeActivityLifecycleCallbacksInner(activity, callbacks)); } private void removeActivityLifecycleCallbacksInner(final Activity activity, @@ -182,13 +172,7 @@ final class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleC return null; } return (Application) app; - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { + } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); } return null; @@ -323,16 +307,13 @@ final class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleC } else { final Object tag = activity.getWindow().getDecorView().getTag(-123); if (!(tag instanceof Integer)) return; - UtilsBridge.runOnUiThreadDelayed(new Runnable() { - @Override - public void run() { - try { - Window window = activity.getWindow(); - if (window != null) { - window.setSoftInputMode(((Integer) tag)); - } - } catch (Exception ignore) { + UtilsBridge.runOnUiThreadDelayed(() -> { + try { + Window window = activity.getWindow(); + if (window != null) { + window.setSoftInputMode(((Integer) tag)); } + } catch (Exception ignore) { } }, 100); } @@ -370,6 +351,9 @@ final class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleC Activity topActivity = null; try { Object activityThread = getActivityThread(); + if(activityThread == null){ + return list; + } Field mActivitiesField = activityThread.getClass().getDeclaredField("mActivities"); mActivitiesField.setAccessible(true); Object mActivities = mActivitiesField.get(activityThread); @@ -448,9 +432,7 @@ final class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleC sDurationScaleField.set(null, 1f); Log.i("UtilsActivityLifecycle", "setAnimatorsEnabled: Animators are enabled now!"); } - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { + } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ZipUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ZipUtils.java index 0c2b7feb0e..df3571d267 100644 --- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ZipUtils.java +++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ZipUtils.java @@ -62,18 +62,11 @@ public final class ZipUtils { final String comment) throws IOException { if (srcFilePaths == null || zipFilePath == null) return false; - ZipOutputStream zos = null; - try { - zos = new ZipOutputStream(new FileOutputStream(zipFilePath)); + try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) { for (String srcFile : srcFilePaths) { if (!zipFile(UtilsBridge.getFileByPath(srcFile), "", zos, comment)) return false; } return true; - } finally { - if (zos != null) { - zos.finish(); - zos.close(); - } } } @@ -104,18 +97,11 @@ public final class ZipUtils { final String comment) throws IOException { if (srcFiles == null || zipFile == null) return false; - ZipOutputStream zos = null; - try { - zos = new ZipOutputStream(new FileOutputStream(zipFile)); + try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) { for (File srcFile : srcFiles) { if (!zipFile(srcFile, "", zos, comment)) return false; } return true; - } finally { - if (zos != null) { - zos.finish(); - zos.close(); - } } } @@ -177,14 +163,8 @@ public final class ZipUtils { final String comment) throws IOException { if (srcFile == null || zipFile == null) return false; - ZipOutputStream zos = null; - try { - zos = new ZipOutputStream(new FileOutputStream(zipFile)); + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) { return zipFile(srcFile, "", zos, comment); - } finally { - if (zos != null) { - zos.close(); - } } } @@ -207,22 +187,16 @@ public final class ZipUtils { } } } else { - InputStream is = null; - try { - is = new BufferedInputStream(new FileInputStream(srcFile)); + try (InputStream is = new BufferedInputStream(new FileInputStream(srcFile))) { ZipEntry entry = new ZipEntry(rootPath); entry.setComment(comment); zos.putNextEntry(entry); - byte buffer[] = new byte[BUFFER_LEN]; + byte[] buffer = new byte[BUFFER_LEN]; int len; while ((len = is.read(buffer, 0, BUFFER_LEN)) != -1) { zos.write(buffer, 0, len); } zos.closeEntry(); - } finally { - if (is != null) { - is.close(); - } } } return true; @@ -330,23 +304,12 @@ public final class ZipUtils { return UtilsBridge.createOrExistsDir(file); } else { if (!UtilsBridge.createOrExistsFile(file)) return false; - InputStream in = null; - OutputStream out = null; - try { - in = new BufferedInputStream(zip.getInputStream(entry)); - out = new BufferedOutputStream(new FileOutputStream(file)); - byte buffer[] = new byte[BUFFER_LEN]; + try (InputStream in = new BufferedInputStream(zip.getInputStream(entry)); OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { + byte[] buffer = new byte[BUFFER_LEN]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } - } finally { - if (in != null) { - in.close(); - } - if (out != null) { - out.close(); - } } } return true; diff --git a/foudations/mogo-aicloud-services-sdk/src/main/java/com/mogo/aicloud/services/socket/MogoAiCloudSocketManager.java b/foudations/mogo-aicloud-services-sdk/src/main/java/com/mogo/aicloud/services/socket/MogoAiCloudSocketManager.java index 8951f10428..ac086c9b57 100644 --- a/foudations/mogo-aicloud-services-sdk/src/main/java/com/mogo/aicloud/services/socket/MogoAiCloudSocketManager.java +++ b/foudations/mogo-aicloud-services-sdk/src/main/java/com/mogo/aicloud/services/socket/MogoAiCloudSocketManager.java @@ -7,7 +7,7 @@ import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_CODE_CLOUD import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_CODE_CLOUD_PASSPORT_TOKEN; import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_CODE_CLOUD_SOCKET_INIT; import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_SOURCE_CLOUD; -import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_TYPE_INIT_STATUS; +import static com.mogo.eagle.core.data.deva.chain.ChainConstant.CHAIN_TYPE_STATUS; import android.content.Context; @@ -78,7 +78,7 @@ public class MogoAiCloudSocketManager extends ConnectionLifecycleListener implem private final Map mAckListeners = new ConcurrentHashMap<>(); @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, parentNodeAliasCode = CHAIN_CODE_CLOUD_PASSPORT_TOKEN, nodeAliasCode = CHAIN_CODE_CLOUD_SOCKET_INIT, @@ -211,7 +211,7 @@ public class MogoAiCloudSocketManager extends ConnectionLifecycleListener implem }; @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, nodeAliasCode = CHAIN_CODE_CLOUD_CONNECT_SUCCESS, paramIndexes = {-1} @@ -228,7 +228,7 @@ public class MogoAiCloudSocketManager extends ConnectionLifecycleListener implem } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, nodeAliasCode = CHAIN_CODE_CLOUD_CONNECT_FAIL, paramIndexes = {-1} @@ -245,7 +245,7 @@ public class MogoAiCloudSocketManager extends ConnectionLifecycleListener implem } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, nodeAliasCode = CHAIN_CODE_CLOUD_CONNECT_LOST, paramIndexes = {-1} @@ -262,7 +262,7 @@ public class MogoAiCloudSocketManager extends ConnectionLifecycleListener implem } @ChainLog( - linkChainLog = CHAIN_TYPE_INIT_STATUS, + linkChainLog = CHAIN_TYPE_STATUS, linkCode = CHAIN_SOURCE_CLOUD, parentNodeAliasCode = CHAIN_CODE_CLOUD_SOCKET_INIT, nodeAliasCode = CHAIN_CODE_CLOUD_CONNECT_ERROR, diff --git a/foudations/mogo-commons/src/main/java/com/mogo/commons/module/status/MogoStatusManager.java b/foudations/mogo-commons/src/main/java/com/mogo/commons/module/status/MogoStatusManager.java index ac60d1a407..6115db7dbf 100644 --- a/foudations/mogo-commons/src/main/java/com/mogo/commons/module/status/MogoStatusManager.java +++ b/foudations/mogo-commons/src/main/java/com/mogo/commons/module/status/MogoStatusManager.java @@ -16,22 +16,15 @@ import java.util.concurrent.ConcurrentHashMap; */ public class MogoStatusManager implements IMogoStatusManager { - private static volatile MogoStatusManager sInstance; - private static final byte[] obj = new byte[0]; - private MogoStatusManager() { - } public static MogoStatusManager getInstance() { - if (sInstance == null) { - synchronized (obj) { - if (sInstance == null) { - sInstance = new MogoStatusManager(); - } - } - } - return sInstance; + return Holder.sInstance; + } + + private static final class Holder{ + private static final MogoStatusManager sInstance = new MogoStatusManager(); } /** diff --git a/gradle.properties b/gradle.properties index 5b0d7d4cf1..d068d9387c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -43,6 +43,9 @@ RELEASE_REPOSITORY_URL=http://nexus.zhidaoauto.com/repository/maven-releases/ SNAPSHOT_REPOSITORY_URL=http://nexus.zhidaoauto.com/repository/maven-snapshots/ USERNAME=xintai PASSWORD=xintai2018 +#sonar配置 +systemProp.sonar.host.url=https://sonarqube.zhidaoauto.com +systemProp.sonar.login=8c54651afe55516ee11edaf3d2aec5e560577096 # 编译模式: false - 依赖本地版本, true - 依赖 maven 版本 USE_MAVEN_PACKAGE=false ##plugin 插件 @@ -58,7 +61,7 @@ bytex.ASM_API=ASM7 ################ 外部依赖引用 ################ # loglib -LOGLIB_VERSION=1.9.17 +LOGLIB_VERSION=1.9.18 ######## MogoAiCloudSDK Version ######## # 网络请求LOGLIB_VERSION MOGO_NETWORK_VERSION=1.4.7.17 diff --git a/gradle/ext.gradle b/gradle/ext.gradle index 2337daae66..7d1e8f2788 100644 --- a/gradle/ext.gradle +++ b/gradle/ext.gradle @@ -2,6 +2,6 @@ ext { gradle_version = '3.5.3' kotlin_plugin_version = '1.5.30' plugin_version = '10.0.0_mogo' - service_chain_version = '5.3.6' + service_chain_version = '5.3.8' lancetx_plugin_version = '10.0.4_mogo' } \ No newline at end of file diff --git a/libraries/mapmodule/src/main/java/com/autonavi/nge/guidance/LaneMarkTools.java b/libraries/mapmodule/src/main/java/com/autonavi/nge/guidance/LaneMarkTools.java index 4145030de4..e7d8fee100 100644 --- a/libraries/mapmodule/src/main/java/com/autonavi/nge/guidance/LaneMarkTools.java +++ b/libraries/mapmodule/src/main/java/com/autonavi/nge/guidance/LaneMarkTools.java @@ -86,8 +86,8 @@ public class LaneMarkTools { { Panel_Image_Scale = scale; - PANEL_IMAGE_WIDTH = (int) (screenWidth/4 * Panel_Image_Scale); - PANEL_IMAGE_HEIGHT = (int) (screenHeight/3 * Panel_Image_Scale); + PANEL_IMAGE_WIDTH = (int) (screenWidth/4.0 * Panel_Image_Scale); + PANEL_IMAGE_HEIGHT = (int) (screenHeight/3.0 * Panel_Image_Scale); LANE_PANELBORDER_MARGIN = (int) (5 * Panel_Image_Scale); LANE_PANELBORDER_RADIAN = (int) (10 * Panel_Image_Scale); @@ -154,12 +154,12 @@ public class LaneMarkTools { paint.setColor(Color.GREEN); paint.setAntiAlias(true); Path path = new Path(); - path.moveTo(ARROW_IMAGE_WIDTH / 2, 0); - path.lineTo(ARROW_IMAGE_WIDTH, ARROW_IMAGE_HEIGHT / 2); - path.lineTo(ARROW_IMAGE_WIDTH, ARROW_IMAGE_HEIGHT / 2 + ARROW_THICKNESS); - path.lineTo(ARROW_IMAGE_WIDTH / 2, ARROW_THICKNESS); - path.lineTo(0, ARROW_IMAGE_HEIGHT / 2 + ARROW_THICKNESS); - path.lineTo(0, ARROW_IMAGE_HEIGHT / 2); + path.moveTo(ARROW_IMAGE_WIDTH / 2.0f, 0); + path.lineTo(ARROW_IMAGE_WIDTH, ARROW_IMAGE_HEIGHT / 2.0f); + path.lineTo(ARROW_IMAGE_WIDTH, ARROW_IMAGE_HEIGHT / 2.0f + ARROW_THICKNESS); + path.lineTo(ARROW_IMAGE_WIDTH / 2.0f, ARROW_THICKNESS); + path.lineTo(0, ARROW_IMAGE_HEIGHT / 2.0f + ARROW_THICKNESS); + path.lineTo(0, ARROW_IMAGE_HEIGHT / 2.0f); path.close(); canvas.drawPath(path, paint); BitmapInfo info = new BitmapInfo(); @@ -186,7 +186,7 @@ public class LaneMarkTools { paint.setColor(Color.GREEN); paint.setAntiAlias(true); Path path = new Path(); - path.moveTo(TRIANGLE_IMAGE_WIDTH / 2, 0); + path.moveTo(TRIANGLE_IMAGE_WIDTH / 2.0f, 0); path.lineTo(TRIANGLE_IMAGE_WIDTH, TRIANGLE_IMAGE_HEIGHT); path.lineTo(0, TRIANGLE_IMAGE_HEIGHT); path.close(); @@ -289,8 +289,8 @@ public class LaneMarkTools { paint.setStyle(Style.STROKE); paint.setStrokeWidth(ARC_GOTO_SECTION_WIDTH); paint.setAntiAlias(true); - float arcGotoSectionPositionX = (LANE_WIDTH - ARC_RADIUS * 2) / 2; - float arcGotoSectionPositionY = LANE_HEIGHT / 3; + float arcGotoSectionPositionX = (LANE_WIDTH - ARC_RADIUS * 2.0f) / 2.0f; + float arcGotoSectionPositionY = LANE_HEIGHT / 3.0f; canvas.drawLine(arcGotoSectionPositionX, arcGotoSectionPositionY, arcGotoSectionPositionX, arcGotoSectionPositionY + ARC_INTO_SECTION_HEIGHT, paint); @@ -320,14 +320,14 @@ public class LaneMarkTools { paint.setStrokeWidth(ARC_GOTO_SECTION_WIDTH); paint.setAntiAlias(true); - float arcGotoSectionPositionX = (LANE_WIDTH - ARC_RADIUS * 2) / 2; - float arcGotoSectionPositionY = LANE_HEIGHT / 3; + float arcGotoSectionPositionX = (LANE_WIDTH - ARC_RADIUS * 2.0f) / 2.0f; + float arcGotoSectionPositionY = LANE_HEIGHT / 3.0f; canvas.drawLine(arcGotoSectionPositionX, arcGotoSectionPositionY, arcGotoSectionPositionX, arcGotoSectionPositionY + ARC_GOTO_SECTION_HEIGHT, paint); float arcIntoSectionPositionX = arcGotoSectionPositionX + ARC_RADIUS * 2; - float arcIntoSectionPositionY = LANE_HEIGHT / 3; + float arcIntoSectionPositionY = LANE_HEIGHT / 3.0f; canvas.drawLine(arcIntoSectionPositionX, arcIntoSectionPositionY, arcIntoSectionPositionX, arcIntoSectionPositionY + ARC_INTO_SECTION_HEIGHT, paint); @@ -348,7 +348,7 @@ public class LaneMarkTools { canvas.save(); canvas.translate(translationX, translationY); canvas.rotate(180); - canvas.drawBitmap(arrowImage, -(arrowImage.getWidth() / 2),0, paint); + canvas.drawBitmap(arrowImage, -(arrowImage.getWidth() / 2.0f),0, paint); canvas.restore(); BitmapInfo info = new BitmapInfo(); @@ -378,7 +378,7 @@ public class LaneMarkTools { paint.setStrokeWidth(STRAIGHT_SECTION_WIDTH); paint.setAntiAlias(true); - Bitmap arrowImage = getRenderArrowImage(isW == AHEAD_BIT_MASK ? false : true).bitmap; + Bitmap arrowImage = getRenderArrowImage(isW != AHEAD_BIT_MASK).bitmap; int arrowPositionX = (LANE_WIDTH - arrowImage.getWidth()) / 2; int arrowPositionY = (LANE_HEIGHT - ARROW_THICKNESS - STRAIGHT_SECTION_HEIGHT) / 2; canvas.drawBitmap(arrowImage, arrowPositionX, arrowPositionY, paint); @@ -429,13 +429,13 @@ public class LaneMarkTools { canvas.drawPath(path, paint); - Bitmap arrowImage = getRenderArrowImage(isW == LEFT_TWO_BIT_MASK ? false : true).bitmap; + Bitmap arrowImage = getRenderArrowImage(isW != LEFT_TWO_BIT_MASK).bitmap; int translationX = endX - ARROW_THICKNESS; int translationY = endY; canvas.save(); canvas.translate(translationX, translationY); canvas.rotate(-90); - canvas.drawBitmap(arrowImage, -(arrowImage.getWidth() / 2), 0, paint); + canvas.drawBitmap(arrowImage, -(arrowImage.getWidth() / 2.0f), 0, paint); canvas.restore(); BitmapInfo info = new BitmapInfo(); @@ -479,13 +479,13 @@ public class LaneMarkTools { canvas.drawPath(path, paint); - Bitmap arrowImage = getRenderArrowImage(isW == RIGHT_TWO_BIT_MASK ? false : true).bitmap; + Bitmap arrowImage = getRenderArrowImage(isW != RIGHT_TWO_BIT_MASK).bitmap; int translationX = endX + ARROW_THICKNESS; int translationY = endY; canvas.save(); canvas.translate(translationX, translationY); canvas.rotate(90); - canvas.drawBitmap(arrowImage, -(arrowImage.getWidth() / 2), 0, paint); + canvas.drawBitmap(arrowImage, -(arrowImage.getWidth() / 2.0f), 0, paint); canvas.restore(); BitmapInfo info = new BitmapInfo(); @@ -707,8 +707,8 @@ public class LaneMarkTools { paint.setStrokeWidth(RIGHT_TURN_VERTICAL_SECTION_WIDTH); paint.setAntiAlias(true); - float startX = LANE_WIDTH / 3; - float startY = LANE_HEIGHT - LANE_HEIGHT / 4; + float startX = LANE_WIDTH / 3.0f; + float startY = LANE_HEIGHT - LANE_HEIGHT / 4.0f; float endX = startX; float endY = startY - RIGHT_TURN_VERTICAL_SECTION_HEIGHT; @@ -717,20 +717,20 @@ public class LaneMarkTools { paint.setStyle(Style.FILL); Path path = new Path(); - path.moveTo(endX - RIGHT_TURN_VERTICAL_SECTION_WIDTH / 2, endY); - path.lineTo(endX - RIGHT_TURN_VERTICAL_SECTION_WIDTH / 2, endY + RIGHT_FRONT_TURN_SLOPE_THICKNESS); - path.lineTo(endX - RIGHT_TURN_VERTICAL_SECTION_WIDTH / 2 + RIGHT_FRONT_TURN_SLOPE_WIDTH, endY); - path.lineTo(endX - RIGHT_TURN_VERTICAL_SECTION_WIDTH / 2 + RIGHT_FRONT_TURN_SLOPE_WIDTH, endY - RIGHT_FRONT_TURN_SLOPE_THICKNESS); + path.moveTo(endX - RIGHT_TURN_VERTICAL_SECTION_WIDTH / 2.0f, endY); + path.lineTo(endX - RIGHT_TURN_VERTICAL_SECTION_WIDTH / 2.0f, endY + RIGHT_FRONT_TURN_SLOPE_THICKNESS); + path.lineTo(endX - RIGHT_TURN_VERTICAL_SECTION_WIDTH / 2.0f + RIGHT_FRONT_TURN_SLOPE_WIDTH, endY); + path.lineTo(endX - RIGHT_TURN_VERTICAL_SECTION_WIDTH / 2.0f + RIGHT_FRONT_TURN_SLOPE_WIDTH, endY - RIGHT_FRONT_TURN_SLOPE_THICKNESS); canvas.drawPath(path, paint); Bitmap triangleImage = getRenderTriangleImage(isW).bitmap; - float translationX = endX - RIGHT_TURN_VERTICAL_SECTION_WIDTH / 2 + RIGHT_FRONT_TURN_SLOPE_WIDTH + TRIANGLE_IMAGE_HEIGHT; - float translationY = endY - RIGHT_FRONT_TURN_SLOPE_THICKNESS / 2; + float translationX = endX - RIGHT_TURN_VERTICAL_SECTION_WIDTH / 2.0f + RIGHT_FRONT_TURN_SLOPE_WIDTH + TRIANGLE_IMAGE_HEIGHT; + float translationY = endY - RIGHT_FRONT_TURN_SLOPE_THICKNESS / 2.0f; canvas.save(); canvas.translate(translationX, translationY); canvas.rotate(90); - canvas.drawBitmap(triangleImage, -(triangleImage.getWidth() / 2), 0, paint); + canvas.drawBitmap(triangleImage, -(triangleImage.getWidth() / 2.0f), 0, paint); canvas.restore(); BitmapInfo info = new BitmapInfo(); @@ -769,10 +769,10 @@ public class LaneMarkTools { paint.setStyle(Style.FILL); Path path = new Path(); - path.moveTo(endX + LEFT_TURN_VERTICAL_SECTION_WIDTH / 2, endY); - path.lineTo(endX + LEFT_TURN_VERTICAL_SECTION_WIDTH / 2, endY + LEFT_FRONT_TURN_SLOPE_THICKNESS); - path.lineTo(endX + LEFT_TURN_VERTICAL_SECTION_WIDTH / 2 - LEFT_FRONT_TURN_SLOPE_WIDTH, endY); - path.lineTo(endX + LEFT_TURN_VERTICAL_SECTION_WIDTH / 2 - LEFT_FRONT_TURN_SLOPE_WIDTH, endY - LEFT_FRONT_TURN_SLOPE_THICKNESS); + path.moveTo(endX + LEFT_TURN_VERTICAL_SECTION_WIDTH / 2.0f, endY); + path.lineTo(endX + LEFT_TURN_VERTICAL_SECTION_WIDTH / 2.0f, endY + LEFT_FRONT_TURN_SLOPE_THICKNESS); + path.lineTo(endX + LEFT_TURN_VERTICAL_SECTION_WIDTH / 2.0f - LEFT_FRONT_TURN_SLOPE_WIDTH, endY); + path.lineTo(endX + LEFT_TURN_VERTICAL_SECTION_WIDTH / 2.0f - LEFT_FRONT_TURN_SLOPE_WIDTH, endY - LEFT_FRONT_TURN_SLOPE_THICKNESS); canvas.drawPath(path, paint); @@ -782,7 +782,7 @@ public class LaneMarkTools { canvas.save(); canvas.translate(translationX, translationY); canvas.rotate(-90); - canvas.drawBitmap(triangleImage, -(triangleImage.getWidth() / 2), 0, paint); + canvas.drawBitmap(triangleImage, -(triangleImage.getWidth() / 2.0f), 0, paint); canvas.restore(); BitmapInfo info = new BitmapInfo(); info.bitmap = bitmap; @@ -807,8 +807,8 @@ public class LaneMarkTools { paint.setStrokeWidth(LEFT_TURN_VERTICAL_SECTION_WIDTH); paint.setAntiAlias(true); - Bitmap leftFrontTurnLaneArrow = getRenderLeftFrontTurnLaneArrow(isW == LEFT_TWO_BIT_MASK?false : true).bitmap; - Bitmap UTurnLaneArrow = getRenderUTurnLaneArrow(isW == UTURN_BIT_MASK?false : true).bitmap; + Bitmap leftFrontTurnLaneArrow = getRenderLeftFrontTurnLaneArrow(isW != LEFT_TWO_BIT_MASK).bitmap; + Bitmap UTurnLaneArrow = getRenderUTurnLaneArrow(isW != UTURN_BIT_MASK).bitmap; int translationX = 0; int translationY = LANE_HEIGHT / 4; @@ -864,8 +864,8 @@ public class LaneMarkTools { Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); - Bitmap UTurnLaneArrow = getRenderUTurnLaneArrow(isW == UTURN_BIT_MASK ? false : true).bitmap; - Bitmap rightFrontTurnLaneArrow = getRenderRightFrontTurnLaneArrow(isW == RIGHT_TWO_BIT_MASK ? false : true).bitmap; + Bitmap UTurnLaneArrow = getRenderUTurnLaneArrow(isW != UTURN_BIT_MASK).bitmap; + Bitmap rightFrontTurnLaneArrow = getRenderRightFrontTurnLaneArrow(isW != RIGHT_TWO_BIT_MASK).bitmap; Paint paint = new Paint(); paint.setColor(Color.WHITE); paint.setStyle(Style.STROKE); @@ -873,7 +873,7 @@ public class LaneMarkTools { paint.setAntiAlias(true); float translationX = -ARC_RADIUS; - float translationY = LANE_HEIGHT / 4; + float translationY = LANE_HEIGHT / 4.0f; canvas.save(); if(isW != UTURN_BIT_MASK) { @@ -884,8 +884,8 @@ public class LaneMarkTools { if(isW != RIGHT_TWO_BIT_MASK) { - translationX = RIGHT_FRONT_TURN_SLOPE_WIDTH / 2; - translationY = -(LANE_HEIGHT / 8); + translationX = RIGHT_FRONT_TURN_SLOPE_WIDTH / 2.0f; + translationY = -(LANE_HEIGHT / 8.0f); canvas.translate(translationX, translationY); canvas.drawBitmap(rightFrontTurnLaneArrow, 0, 0, paint); canvas.translate(-translationX, -translationY); @@ -894,15 +894,15 @@ public class LaneMarkTools { if(isW == UTURN_BIT_MASK) { translationX = -ARC_RADIUS; - translationY = LANE_HEIGHT / 4; + translationY = LANE_HEIGHT / 4.0f; canvas.translate(translationX, translationY); canvas.drawBitmap(UTurnLaneArrow, 0, 0, paint); canvas.translate(-translationX, -translationY); } else if(isW == RIGHT_TWO_BIT_MASK) { - translationX = RIGHT_FRONT_TURN_SLOPE_WIDTH / 2; - translationY = -(LANE_HEIGHT / 8); + translationX = RIGHT_FRONT_TURN_SLOPE_WIDTH / 2.0f; + translationY = -(LANE_HEIGHT / 8.0f); canvas.translate(translationX, translationY); canvas.drawBitmap(rightFrontTurnLaneArrow, 0, 0, paint); canvas.translate(-translationX, -translationY); @@ -918,7 +918,7 @@ public class LaneMarkTools { return info; } - //直行 + 左转 + 右转ֱ�� + ��ת + ��ת + //直行 + 左转 + 右转 public BitmapInfo getRenderStraightAddLeftRightTurnLaneArrow(int isW) { int width = LANE_WIDTH; @@ -934,8 +934,8 @@ public class LaneMarkTools { paint.setAntiAlias(true); Bitmap straightLaneArrow = getRenderStraightLaneArrow(isW).bitmap; - Bitmap leftFrontTurnArrow = getRenderLeftFrontTurnLaneArrow(isW == LEFT_TWO_BIT_MASK ? false : true).bitmap; - Bitmap RightFrontTurnArrow = getRenderRightFrontTurnLaneArrow(isW == RIGHT_TWO_BIT_MASK ? false : true).bitmap; + Bitmap leftFrontTurnArrow = getRenderLeftFrontTurnLaneArrow(isW != LEFT_TWO_BIT_MASK).bitmap; + Bitmap RightFrontTurnArrow = getRenderRightFrontTurnLaneArrow(isW != RIGHT_TWO_BIT_MASK).bitmap; int translationX = -(LEFT_FRONT_TURN_SLOPE_WIDTH / 2); int translationY = LANE_HEIGHT / 6; canvas.save(); @@ -1015,7 +1015,7 @@ public class LaneMarkTools { paint.setAntiAlias(true); Bitmap straightLaneArrow = getRenderStraightLaneArrow(type).bitmap; - Bitmap UTurnLaneArrow = getRenderUTurnLaneArrow(type == UTURN_BIT_MASK ? false : true).bitmap; + Bitmap UTurnLaneArrow = getRenderUTurnLaneArrow(type != UTURN_BIT_MASK).bitmap; int translationX = -ARC_RADIUS; int translationY = LANE_HEIGHT / 4; @@ -1228,7 +1228,7 @@ public class LaneMarkTools { }else if(mark.isUTurn) { //获取 "调头" 车道箭头图元 - bitmap = getRenderUTurnLaneArrow(highType == UTURN_BIT_MASK ? false : true); + bitmap = getRenderUTurnLaneArrow(highType != UTURN_BIT_MASK); } return bitmap; diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/byteh/PayloadEncoder.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/byteh/PayloadEncoder.java index bdc6ed5c2f..0d2bd9d0d8 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/byteh/PayloadEncoder.java +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/byteh/PayloadEncoder.java @@ -3,7 +3,6 @@ package com.zhidaoauto.map.sdk.inner.byteh; import com.autonavi.nge.map.LonLat; import java.lang.reflect.Field; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; @@ -14,7 +13,7 @@ public class PayloadEncoder { public static byte[] getPayload(T command) { List fieldWrapperList = command.getFieldWrapperList(); ByteBuf buffer = Unpooled.buffer(); - for(FieldWrapper fieldWrapper :fieldWrapperList){ + for (FieldWrapper fieldWrapper : fieldWrapperList) { write2ByteBuf(fieldWrapper, command, buffer); } return buffer.array(); @@ -37,6 +36,9 @@ public class PayloadEncoder { } catch (IllegalAccessException e) { new RuntimeException("反射获取值失败,filed:" + field.getName(), e); } + if (value == null) { + return; + } switch (typeName) { case "com.autonavi.nge.map.LonLat": LonLat lonLat = (LonLat) value; @@ -51,6 +53,8 @@ public class PayloadEncoder { case "java.lang.Character": case "kotlin.Character": case "char": + case "java.lang.String": + case "kotlin.String": buffer.writeCharSequence((CharSequence) value, StandardCharsets.UTF_8); break; case "java.lang.Byte": @@ -83,10 +87,6 @@ public class PayloadEncoder { case "double": buffer.writeDouble((double) value); break; - case "java.lang.String": - case "kotlin.String": - buffer.writeCharSequence((CharSequence) value, StandardCharsets.UTF_8); - break; default: throw new RuntimeException(typeName + "不支持,bug"); } diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/element/M3DCar.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/element/M3DCar.java index 6b2afa8ef1..6fb688aea9 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/element/M3DCar.java +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/element/M3DCar.java @@ -6,13 +6,13 @@ import java.io.DataInputStream; import java.io.IOException; public class M3DCar { - private Context context; - private int resid; + private final Context context; + private final int redis; public byte[] totBuffer = null; public int totSize = 0; - public M3DCar(Context context, int resid) { - this.resid = resid; + public M3DCar(Context context, int redis) { + this.redis = redis; this.context = context; loadData(); } @@ -20,12 +20,12 @@ public class M3DCar { private void loadData() { if (null != totBuffer) return; - DataInputStream dis = new DataInputStream(context.getResources().openRawResource(resid)); + ; int curTotSize = 64 * 1024; totBuffer = new byte[curTotSize]; byte[] buffer = new byte[1024]; - int size = 0; - try { + int size; + try(DataInputStream dis = new DataInputStream(context.getResources().openRawResource(redis))) { while ((size = dis.read(buffer)) >= 0) { if (totSize + size > curTotSize) { curTotSize = (totSize + size) * 3 / 2; @@ -36,8 +36,8 @@ public class M3DCar { System.arraycopy(buffer, 0, totBuffer, totSize, size); totSize += size; } - dis.close(); } catch (IOException e) { + e.printStackTrace(); } } } diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/marker/MarkerNativeInterface.kt b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/marker/MarkerNativeInterface.kt index 547a375661..bb3c70f27c 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/marker/MarkerNativeInterface.kt +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/marker/MarkerNativeInterface.kt @@ -170,7 +170,7 @@ class MarkerNativeInterface(private val mMapController: IMapController): IMarker if(markerBytes.isEmpty()){ return } - MD5Utils.getInstanse() + MD5Utils.getInstance() val markerIconName = MD5Utils.getMD5String(markerBytes) //缓存图片 if (!containMarkerIcon(markerIconName)) { diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/DirectionLayer.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/DirectionLayer.java index ca863d4d06..985a9eb154 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/DirectionLayer.java +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/DirectionLayer.java @@ -23,8 +23,8 @@ public class DirectionLayer extends ImageView implements MapStatusListener { private static final String TAG = "DirectionLayer"; private Drawable icon; private IMapController mMapController; - private Matrix matrix = new Matrix(); - private Camera mCamera = new Camera(); + private final Matrix matrix = new Matrix(); + private final Camera mCamera = new Camera(); public DirectionLayer(Context context){ super(context); @@ -81,14 +81,14 @@ public class DirectionLayer extends ImageView implements MapStatusListener { return; } canvas.save(); - canvas.translate(getWidth() / 2, getHeight() / 2); + canvas.translate(getWidth() / 2.0f, getHeight() / 2.0f); // mCamera.save(); // mCamera.rotateX(90 - mapController.getDAngle()); // mCamera.getMatrix(matrix); // mCamera.restore(); canvas.concat(matrix); canvas.rotate(mMapController.getMapViewRotation()); - canvas.translate(-getWidth() / 2, -getHeight() / 2); + canvas.translate(-getWidth() / 2.0f, -getHeight() / 2.0f); super.onDraw(canvas); canvas.restore(); postInvalidate(); diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/SatelliteSkyView.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/SatelliteSkyView.java index 5ca03e064a..22732e9d7d 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/SatelliteSkyView.java +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/SatelliteSkyView.java @@ -30,850 +30,835 @@ import java.util.Iterator; public class SatelliteSkyView extends View { - private int text1_x = 66; - private int text2_x = 165; - private int text3_x = 340; - private int text4_x = 46; - private int text5_x = 210; - private int text6_x = 377; - private int text1_y = 57; - private int text2_y = 57; - private int text3_y = 57; - private int text4_y = 133; - private int text5_y = 133; - private int text6_y = 133; - private int radius = 130;// 星球半径 - private int centerX = 240;// 星球中心点x值 - private int centerY = 425;// 星球中心点y值 - private int ballR = 35; // 小球半径 - private int redR = 175; - private int settingX=460; - private int settingY=670; + private int text1_x = 66; + private int text2_x = 165; + private int text3_x = 340; + private int text4_x = 46; + private int text5_x = 210; + private int text6_x = 377; + private int text1_y = 57; + private int text2_y = 57; + private int text3_y = 57; + private int text4_y = 133; + private int text5_y = 133; + private int text6_y = 133; + private int radius = 130;// 星球半径 + private int centerX = 240;// 星球中心点x值 + private int centerY = 425;// 星球中心点y值 + private int ballR = 35; // 小球半径 + private int redR = 175; + private int settingX = 460; + private int settingY = 670; - private Paint mGridPaint; - private Paint mTextPaint; - private Paint mBackground; + private final Paint mGridPaint; + private final Paint mTextPaint; - private Bitmap mbg; - private Bitmap[] number = new Bitmap[10]; - private Bitmap[] lNumber = new Bitmap[10]; - private Bitmap water; - private Bitmap arrow; - private Bitmap sector; - private Bitmap dot; - private Bitmap greenDot; - private Bitmap grayDot; - private Bitmap yellowDot; - - private int signalBottom; - private int signalTop; - private int[] signalX = new int[12]; - private int signalWidth; - private float degree = 0; - private float acc = 0; - private float dirX = 0; - private float dirY = 0; - private float m_sensorDir = 0; - private float[] lastA = new float[3]; - private float[] initA = new float[3]; - private boolean start = false; - private int count = 0; - private int m_nScreenWidth = 0; - private int m_nScreenHeight = 0; - int nDispH = this.getHeight(); + private Bitmap mbg; + private final Bitmap[] number = new Bitmap[10]; + private final Bitmap[] lNumber = new Bitmap[10]; + private Bitmap water; + private Bitmap arrow; + private Bitmap sector; + private Bitmap dot; + private Bitmap greenDot; + private Bitmap grayDot; + private Bitmap yellowDot; - private float x; //水珠坐标 - private float y; - private float nx;//水珠重力坐标 - private float ny; - private float sx = -80; //雷达坐标 - private float sy = -165; - private double dx;//三角变换 - private double dy; - private int delayCount = 0; - private float m_AccX; - private float m_AccY; - private int lastDir = 0; - private float v = 2; - private GradientDrawable mDrawable; - private Paint blackPaint; + private int signalBottom; + private int signalTop; + private final int[] signalX = new int[12]; + private int signalWidth; + private float degree = 0; + private float acc = 0; + private float dirX = 0; + private float dirY = 0; + private float m_sensorDir = 0; + private final float[] lastA = new float[3]; + private final float[] initA = new float[3]; + private boolean start = false; + private int count = 0; + private int m_nScreenWidth = 0; + private int m_nScreenHeight = 0; + int nDispH = this.getHeight(); - private float mBitmapAdjustment; + private float x; //水珠坐标 + private float y; + private float nx;//水珠重力坐标 + private float ny; + private float sx = -80; //雷达坐标 + private float sy = -165; + private double dx;//三角变换 + private double dy; + private int delayCount = 0; + private float m_AccX; + private float m_AccY; + private int lastDir = 0; + private final float v = 2; + private final GradientDrawable mDrawable; + private final Paint blackPaint; - public final static int MAX_SATS = 12; + private final float mBitmapAdjustment; - private int mSatellites; - private int[] mPrns = null; - private float[] mElevation = null; - private float[] mAzimuth = null; - private float[] mSnrs = null; - private float[] mX = null; - private float[] mY = null; - private int mUsedInFixMask = 0; - private double lon = 0; - private double lat = 0; + public final static int MAX_SATS = 12; - // 画信号强度 - private Paint mLinePaint; - private Paint mBarPaintUsed; - private Paint mBarPaintUnused; - private Paint mBarPaintNoFix; - private Paint mBarOutlinePaint; + private int mSatellites; + private int[] mPrns = null; + private float[] mElevation = null; + private float[] mAzimuth = null; + private float[] mSnrs = null; + private float[] mX = null; + private float[] mY = null; + private int mUsedInFixMask = 0; + private double lon = 0; + private double lat = 0; - private double mAlt = 0; - private long mTime = -1; - private int mSpeed = 0; - // 横竖屏模式 - private boolean m_bW = false; - private int m_nDensity = 240; - private boolean flagDir = false; - private boolean flagBall = false; - private SensorManager sensorManager; - - private float fltScale = 0f; - - private Bitmap bitmap; - - private Bitmap setting; - - private GpsStatus gsv = null;; - - public void setExtraInfo(double a, long t, int s) { - this.mAlt = a; - this.mTime = t; - this.mSpeed = s; - } + // 画信号强度 + private final Paint mLinePaint; + private final Paint mBarPaintUsed; + private final Paint mBarPaintUnused; + private final Paint mBarPaintNoFix; + private final Paint mBarOutlinePaint; - private void computeXY() { - for (int i = 0; i < mSatellites; ++i) { - double theta = -(mAzimuth[i] - 90); - double rad = theta * Math.PI / 180.0; - mX[i] = (float) Math.cos(rad); - mY[i] = -(float) Math.sin(rad); - mElevation[i] = 90 - mElevation[i]; - } - } + private double mAlt = 0; + private long mTime = -1; + private int mSpeed = 0; + // 横竖屏模式 + private boolean m_bW = false; + private int m_nDensity = 240; + private boolean flagDir = false; + private boolean flagBall = false; + private final SensorManager sensorManager; - private float[] gacc = new float[3]; - private float[] dir = new float[3]; - private float[] lacc = new float[3]; - private long curTime = 0; + private float fltScale = 0f; - private final SensorEventListener sensorEventListener = new SensorEventListener() { - @Override - public void onSensorChanged(SensorEvent event) { - if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) { - lacc[0] = event.values[0]; - lacc[1] = event.values[1]; - lacc[2] = event.values[2]; - }else if(event.sensor.getType() == Sensor.TYPE_ORIENTATION){ - dir[0] = event.values[0]; - dir[1] = event.values[1]; - dir[2] = event.values[2]; - }else if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){ - gacc[0] = event.values[0]; - gacc[1] = event.values[1]; - gacc[2] = event.values[2]; - } - if(curTime == 0) { - curTime = System.currentTimeMillis(); - } else if(System.currentTimeMillis() - curTime > 50){ - curTime = System.currentTimeMillis(); - update(gacc, dir, lacc); - invalidate(); - } - } + private Bitmap bitmap; - @Override - public void onAccuracyChanged(Sensor arg0, int arg1) { + private Bitmap setting; - - } - }; - private Context mContext; - - public void Resume() { - sensorManager.registerListener( - sensorEventListener, - sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), - SensorManager.SENSOR_DELAY_FASTEST - ); - sensorManager.registerListener( - sensorEventListener, - sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), - SensorManager.SENSOR_DELAY_FASTEST - ); - sensorManager.registerListener( - sensorEventListener, - sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), - SensorManager.SENSOR_DELAY_FASTEST - ); - } - - public void Destroy() { - sensorManager.unregisterListener(sensorEventListener); - } - - public SatelliteSkyView(Context context) { - super(context); - mContext = context; - sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); - curTime = 0; - int nbgID = R.mipmap.navi_gpssv; - { - // 竖屏 + private final GpsStatus gsv = null; + + public void setExtraInfo(double a, long t, int s) { + this.mAlt = a; + this.mTime = t; + this.mSpeed = s; + } + + private void computeXY() { + for (int i = 0; i < mSatellites; ++i) { + double theta = -(mAzimuth[i] - 90); + double rad = theta * Math.PI / 180.0; + mX[i] = (float) Math.cos(rad); + mY[i] = -(float) Math.sin(rad); + mElevation[i] = 90 - mElevation[i]; + } + } + + private final float[] gacc = new float[3]; + private final float[] dir = new float[3]; + private final float[] lacc = new float[3]; + private long curTime = 0; + + private final SensorEventListener sensorEventListener = new SensorEventListener() { + @Override + public void onSensorChanged(SensorEvent event) { + if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) { + lacc[0] = event.values[0]; + lacc[1] = event.values[1]; + lacc[2] = event.values[2]; + } else if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { + dir[0] = event.values[0]; + dir[1] = event.values[1]; + dir[2] = event.values[2]; + } else if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { + gacc[0] = event.values[0]; + gacc[1] = event.values[1]; + gacc[2] = event.values[2]; + } + if (curTime == 0) { + curTime = System.currentTimeMillis(); + } else if (System.currentTimeMillis() - curTime > 50) { + curTime = System.currentTimeMillis(); + update(gacc, dir, lacc); + invalidate(); + } + } + + @Override + public void onAccuracyChanged(Sensor arg0, int arg1) { + + + } + }; + private Context mContext; + + public void Resume() { + sensorManager.registerListener( + sensorEventListener, + sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), + SensorManager.SENSOR_DELAY_FASTEST + ); + sensorManager.registerListener( + sensorEventListener, + sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), + SensorManager.SENSOR_DELAY_FASTEST + ); + sensorManager.registerListener( + sensorEventListener, + sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), + SensorManager.SENSOR_DELAY_FASTEST + ); + } + + public void Destroy() { + sensorManager.unregisterListener(sensorEventListener); + } + + public SatelliteSkyView(Context context) { + super(context); + mContext = context; + sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); + curTime = 0; + int nbgID = R.mipmap.navi_gpssv; + { + // 竖屏 x = centerX; y = centerY; - - //信号显示位置设置 - signalTop = 719; - signalBottom = 782; - signalWidth = 13; - signalX[0] =31; - for(int i=1 ; i<12; i++){ - signalX[i] = signalX[i-1]+37; - if(i>=3 && i<=6){ - signalX[i]++; + + //信号显示位置设置 + signalTop = 719; + signalBottom = 782; + signalWidth = 13; + signalX[0] = 31; + for (int i = 1; i < 12; i++) { + signalX[i] = signalX[i - 1] + 37; + if (i >= 3 && i <= 6) { + signalX[i]++; + } } - } - } - mDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, - new int[] { 0xff7bd497, 0x557bd497 });//13d346 - blackPaint = new Paint(); - blackPaint.setStrokeWidth(13); - blackPaint.setAlpha(255); - blackPaint.setARGB(255, 7, 7, 7); + } + mDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, + new int[]{0xff7bd497, 0x557bd497});//13d346 + blackPaint = new Paint(); + blackPaint.setStrokeWidth(13); + blackPaint.setAlpha(255); + blackPaint.setARGB(255, 7, 7, 7); - try { - mbg = decodeResource(this.getResources(), nbgID); - setting = decodeResource(this.getResources(), R.mipmap.navi_gps_set); - number[0] = decodeResource(this.getResources(), R.mipmap.n0); - number[1] = decodeResource(this.getResources(), R.mipmap.n1); - number[2] = decodeResource(this.getResources(), R.mipmap.n2); - number[3] = decodeResource(this.getResources(), R.mipmap.n3); - number[4] = decodeResource(this.getResources(), R.mipmap.n4); - number[5] = decodeResource(this.getResources(), R.mipmap.n5); - number[6] = decodeResource(this.getResources(), R.mipmap.n6); - number[7] = decodeResource(this.getResources(), R.mipmap.n7); - number[8] = decodeResource(this.getResources(), R.mipmap.n8); - number[9] = decodeResource(this.getResources(), R.mipmap.n9); - - lNumber[0] = decodeResource(this.getResources(), R.mipmap.l0); - lNumber[1] = decodeResource(this.getResources(), R.mipmap.l1); - lNumber[2] = decodeResource(this.getResources(), R.mipmap.l2); - lNumber[3] = decodeResource(this.getResources(), R.mipmap.l3); - lNumber[4] = decodeResource(this.getResources(), R.mipmap.l4); - lNumber[5] = decodeResource(this.getResources(), R.mipmap.l5); - lNumber[6] = decodeResource(this.getResources(), R.mipmap.l6); - lNumber[7] = decodeResource(this.getResources(), R.mipmap.l7); - lNumber[8] = decodeResource(this.getResources(), R.mipmap.l8); - lNumber[9] = decodeResource(this.getResources(), R.mipmap.l9); - - water = decodeResource(this.getResources(), R.mipmap.water); - arrow = decodeResource(this.getResources(), R.mipmap.arrow); - sector = decodeResource(this.getResources(), R.mipmap.sector); - dot = decodeResource(this.getResources(), R.mipmap.dot); - - greenDot = decodeResource(this.getResources(), R.mipmap.green_dot); - grayDot = decodeResource(this.getResources(), R.mipmap.gray_dot); - yellowDot = decodeResource(this.getResources(), R.mipmap.yellow_dot); - - float fltWScale = 1.0f * this.getWidth() / mbg.getWidth(); - float fltHScale = 1.0f * this.getHeight() / mbg.getHeight(); - - if(fltWScale > fltHScale){ - fltScale = fltHScale; - } - else{ - fltScale = fltWScale; - } - } catch (Exception ex) { - ex.printStackTrace(); - } + try { + mbg = decodeResource(this.getResources(), nbgID); + setting = decodeResource(this.getResources(), R.mipmap.navi_gps_set); + number[0] = decodeResource(this.getResources(), R.mipmap.n0); + number[1] = decodeResource(this.getResources(), R.mipmap.n1); + number[2] = decodeResource(this.getResources(), R.mipmap.n2); + number[3] = decodeResource(this.getResources(), R.mipmap.n3); + number[4] = decodeResource(this.getResources(), R.mipmap.n4); + number[5] = decodeResource(this.getResources(), R.mipmap.n5); + number[6] = decodeResource(this.getResources(), R.mipmap.n6); + number[7] = decodeResource(this.getResources(), R.mipmap.n7); + number[8] = decodeResource(this.getResources(), R.mipmap.n8); + number[9] = decodeResource(this.getResources(), R.mipmap.n9); - mGridPaint = new Paint(); - mGridPaint.setColor(0xFFDDDDDD); - mGridPaint.setAntiAlias(true); - mGridPaint.setStyle(Style.STROKE); - mGridPaint.setStrokeWidth(1.0f); + lNumber[0] = decodeResource(this.getResources(), R.mipmap.l0); + lNumber[1] = decodeResource(this.getResources(), R.mipmap.l1); + lNumber[2] = decodeResource(this.getResources(), R.mipmap.l2); + lNumber[3] = decodeResource(this.getResources(), R.mipmap.l3); + lNumber[4] = decodeResource(this.getResources(), R.mipmap.l4); + lNumber[5] = decodeResource(this.getResources(), R.mipmap.l5); + lNumber[6] = decodeResource(this.getResources(), R.mipmap.l6); + lNumber[7] = decodeResource(this.getResources(), R.mipmap.l7); + lNumber[8] = decodeResource(this.getResources(), R.mipmap.l8); + lNumber[9] = decodeResource(this.getResources(), R.mipmap.l9); - mBackground = new Paint(); - mBackground.setColor(0xFF4444DD); + water = decodeResource(this.getResources(), R.mipmap.water); + arrow = decodeResource(this.getResources(), R.mipmap.arrow); + sector = decodeResource(this.getResources(), R.mipmap.sector); + dot = decodeResource(this.getResources(), R.mipmap.dot); - mTextPaint = new Paint(); - mTextPaint.setAntiAlias(true); - mTextPaint.setColor(0xFFFFFFFF); + greenDot = decodeResource(this.getResources(), R.mipmap.green_dot); + grayDot = decodeResource(this.getResources(), R.mipmap.gray_dot); + yellowDot = decodeResource(this.getResources(), R.mipmap.yellow_dot); - mTextPaint.setTextSize(16); - mTextPaint.setTextAlign(Align.CENTER); + float fltWScale = 1.0f * this.getWidth() / mbg.getWidth(); + float fltHScale = 1.0f * this.getHeight() / mbg.getHeight(); - mBitmapAdjustment = 10; + fltScale = Math.min(fltWScale, fltHScale); + } catch (Exception ex) { + ex.printStackTrace(); + } - mLinePaint = new Paint(); - mLinePaint.setColor(0xFFDDDDDD); - mLinePaint.setAntiAlias(true); - mLinePaint.setStyle(Style.STROKE); - mLinePaint.setStrokeWidth(1.0f); + mGridPaint = new Paint(); + mGridPaint.setColor(0xFFDDDDDD); + mGridPaint.setAntiAlias(true); + mGridPaint.setStyle(Style.STROKE); + mGridPaint.setStrokeWidth(1.0f); - mBarPaintUsed = new Paint(); - mBarPaintUsed.setColor(0xFF00BB00); - mBarPaintUsed.setAntiAlias(true); - mBarPaintUsed.setStyle(Style.FILL); - mBarPaintUsed.setStrokeWidth(1.0f); + Paint mBackground = new Paint(); + mBackground.setColor(0xFF4444DD); - mBarPaintUnused = new Paint(mBarPaintUsed); - mBarPaintUnused.setColor(0xFFFFCC33); + mTextPaint = new Paint(); + mTextPaint.setAntiAlias(true); + mTextPaint.setColor(0xFFFFFFFF); - mBarPaintNoFix = new Paint(mBarPaintUsed); - mBarPaintNoFix.setStyle(Style.STROKE); + mTextPaint.setTextSize(16); + mTextPaint.setTextAlign(Align.CENTER); - mBarOutlinePaint = new Paint(); - mBarOutlinePaint.setColor(0xFFFFFFFF); - mBarOutlinePaint.setAntiAlias(true); - mBarOutlinePaint.setStyle(Style.STROKE); - mBarOutlinePaint.setStrokeWidth(1.0f); - } + mBitmapAdjustment = 10; - public void setLonLat(double lon, double lat) { - this.lon = lon; - this.lat = lat; - } + mLinePaint = new Paint(); + mLinePaint.setColor(0xFFDDDDDD); + mLinePaint.setAntiAlias(true); + mLinePaint.setStyle(Style.STROKE); + mLinePaint.setStrokeWidth(1.0f); - @Override - protected void onSizeChanged(int w, int h, int oldw, int oldh) { + mBarPaintUsed = new Paint(); + mBarPaintUsed.setColor(0xFF00BB00); + mBarPaintUsed.setAntiAlias(true); + mBarPaintUsed.setStyle(Style.FILL); + mBarPaintUsed.setStrokeWidth(1.0f); - boolean bReset = false; - int nbgID = R.mipmap.navi_gpssv; + mBarPaintUnused = new Paint(mBarPaintUsed); + mBarPaintUnused.setColor(0xFFFFCC33); + + mBarPaintNoFix = new Paint(mBarPaintUsed); + mBarPaintNoFix.setStyle(Style.STROKE); + + mBarOutlinePaint = new Paint(); + mBarOutlinePaint.setColor(0xFFFFFFFF); + mBarOutlinePaint.setAntiAlias(true); + mBarOutlinePaint.setStyle(Style.STROKE); + mBarOutlinePaint.setStrokeWidth(1.0f); + } + + public void setLonLat(double lon, double lat) { + this.lon = lon; + this.lat = lat; + } + + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + + boolean bReset; + int nbgID = R.mipmap.navi_gpssv; mbg = decodeResource(this.getResources(), nbgID); - - float fltWScale = 1.0f * w / mbg.getWidth(); - float fltHScale = 1.0f * h / mbg.getHeight(); - - if(fltWScale > fltHScale){ - fltScale = fltHScale; - } - else{ - fltScale = fltWScale; - } - if (this.getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { - if (!m_bW) { - return; - } - bReset = true; - // 竖屏 - text1_x = 111; - text2_x = 280; - text3_x = 540; - text4_x = 94; - text5_x = 334; - text6_x = 565; - text1_y = 95; - text2_y = 95; - text3_y = 95; - text4_y = 208; - text5_y = 208; - text6_y = 208; - - settingX=460; - settingY=670; - - radius = 186; - centerX = 360; - centerY = 638; - x = centerX; - y = centerY; - redR = 295; + float fltWScale = 1.0f * w / mbg.getWidth(); + float fltHScale = 1.0f * h / mbg.getHeight(); + + fltScale = Math.min(fltWScale, fltHScale); + if (this.getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { + if (!m_bW) { + return; + } + + bReset = true; + // 竖屏 + text1_x = 111; + text2_x = 280; + text3_x = 540; + text4_x = 94; + text5_x = 334; + text6_x = 565; + text1_y = 95; + text2_y = 95; + text3_y = 95; + text4_y = 208; + text5_y = 208; + text6_y = 208; + + settingX = 460; + settingY = 670; + + radius = 186; + centerX = 360; + centerY = 638; + x = centerX; + y = centerY; + redR = 295; sx = -185; sy = -195; - //信号显示位置设置 - signalTop = 1074; - signalBottom = 1171; - signalWidth = 20; - signalX[0] =48; - for(int i=1 ; i<12; i++){ - signalX[i] = signalX[i-1]+55; - if(i>=3 && i<=6){ - signalX[i]++; - } - } + //信号显示位置设置 + signalTop = 1074; + signalBottom = 1171; + signalWidth = 20; + signalX[0] = 48; + for (int i = 1; i < 12; i++) { + signalX[i] = signalX[i - 1] + 55; + if (i >= 3 && i <= 6) { + signalX[i]++; + } + } sector = decodeResource(this.getResources(), R.mipmap.sector); m_bW = false; - } else { - if (m_bW) { - return; - } - - bReset = true; - // 横屏 - text1_x = 135; - text2_x = 60; - text3_x = 85; - text4_x = 120; - text5_x = 120; - text6_x = 135; - text1_y = 85; - text2_y = 600; - text3_y = 290; - text4_y = 500; - text5_y = 400; - text6_y = 190; - - radius = 172; - centerX = 645; - centerY = 335; - x = centerX; - y = centerY; - sx = -184; - sy = -186; - redR = 275; - //信号显示位置设置 - signalTop = 1193; - signalBottom = 1089; - signalWidth = 20; - signalX[0] =57; - for(int i=1 ; i<12; i++){ - signalX[i] = signalX[i-1]+50; - if(i>=3 && i<=6){ - signalX[i]++; - } + } else { + if (m_bW) { + return; } - m_nScreenWidth = this.getWidth(); - m_nScreenHeight = this.getHeight(); - //nbgID = R.mipmap.navi_gpssv_h; - //sector = decodeResource(this.getResources(), R.mipmap.sector1); - m_bW = true; - } - if (bReset) { - try { - mbg = decodeResource(this.getResources(), nbgID); - if(bitmap != null){ - bitmap.recycle(); - bitmap = null; - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } + bReset = true; + // 横屏 + text1_x = 135; + text2_x = 60; + text3_x = 85; + text4_x = 120; + text5_x = 120; + text6_x = 135; + text1_y = 85; + text2_y = 600; + text3_y = 290; + text4_y = 500; + text5_y = 400; + text6_y = 190; - super.onSizeChanged(w, h, oldw, oldh); - } + radius = 172; + centerX = 645; + centerY = 335; + x = centerX; + y = centerY; + sx = -184; + sy = -186; + redR = 275; + //信号显示位置设置 + signalTop = 1193; + signalBottom = 1089; + signalWidth = 20; + signalX[0] = 57; + for (int i = 1; i < 12; i++) { + signalX[i] = signalX[i - 1] + 50; + if (i >= 3 && i <= 6) { + signalX[i]++; + } + } + m_nScreenWidth = this.getWidth(); + m_nScreenHeight = this.getHeight(); + //nbgID = R.mipmap.navi_gpssv_h; + //sector = decodeResource(this.getResources(), R.mipmap.sector1); + m_bW = true; + } - @Override - protected void onDraw(Canvas canvas) { + if (bReset) { + try { + mbg = decodeResource(this.getResources(), nbgID); + if (bitmap != null) { + bitmap.recycle(); + bitmap = null; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } - super.onDraw(canvas); - int nDispW = this.getWidth(); - int nDispH = this.getHeight(); - int nBgWidth = mbg.getWidth(); - int nBgHeight = mbg.getHeight(); - - m_nScreenWidth = nDispW; - m_nScreenHeight = nDispH; - - if(bitmap == null){ - bitmap = Bitmap.createBitmap(mbg.getWidth(), mbg.getHeight(), Bitmap.Config.RGB_565); - } - - canvas.setDensity(m_nDensity); - bitmap.setDensity(m_nDensity); - Canvas tmpCanvas = new Canvas(bitmap); - drawView(tmpCanvas); - - int nBgW = (int)(fltScale * nBgWidth); - int nBgH = (int)(fltScale * nBgHeight); - Rect src = new Rect(0, 0, nBgWidth, nBgHeight); - Rect dst = new Rect((nDispW-nBgW)/2, (nDispH-nBgH)/2, (nDispW+nBgW)/2, (nDispH+nBgH)/2); - canvas.drawBitmap(bitmap, src, dst, null); - } + super.onSizeChanged(w, h, oldw, oldh); + } - private void drawView(Canvas canvas){ - if(null == canvas){ - return; - } - canvas.drawBitmap(mbg, 0, 0, null); - canvas.drawBitmap(setting, settingX-setting.getWidth(), settingY-setting.getHeight(), null); - //气泡 - if(!m_bW) { - canvas.drawBitmap(water, x-ballR, y-ballR, null); - } else{ - if(m_AccX > 3){ - canvas.drawBitmap(water, centerX + (y - centerY) - ballR, centerY - (x - centerX) - ballR, null); - flagBall = true; - }else if(m_AccX < -3){ - canvas.drawBitmap(water, centerX - (y - centerY) - ballR, centerY + (x - centerX) - ballR, null); - flagBall = false; - }else{ - if(flagBall) { - canvas.drawBitmap(water, centerX + (y - centerY) - ballR, centerY - (x - centerX) - ballR, null); - } else { - canvas.drawBitmap(water, centerX - (y - centerY) - ballR, centerY + (x - centerX) - ballR, null); - } - } - } - - - //罗盘箭头 - float dirTmp = m_sensorDir; - if(m_bW){ - if(m_AccX > 3){ - m_sensorDir = (m_sensorDir + 90) % 360; - flagDir = true; - }else if(m_AccX < -3){ - m_sensorDir = (m_sensorDir - 90 + 360) % 360; - flagDir = false; - }else{ - if(flagDir) { - m_sensorDir = (m_sensorDir + 90) % 360; - } else { - m_sensorDir = (m_sensorDir - 90 + 360) % 360; - } - } - } - canvas.save(); - canvas.translate(centerX, centerY); - int ndir = (int)m_sensorDir; - m_sensorDir = dirTmp; - int delta = ((360 - ndir) - lastDir + 360) % 360; - if(delta > 2){ - if(delta < 180){ - lastDir = (lastDir + 1 + delta / 3) % 360; - }else{ - lastDir = (lastDir - 1 - (360-delta) / 3+ 360) % 360; - } - } - canvas.rotate(lastDir); - canvas.drawBitmap(arrow, (float)-15, (float)(-redR-45), null); - canvas.restore(); + @Override + protected void onDraw(Canvas canvas) { + + super.onDraw(canvas); + int nDispW = this.getWidth(); + int nDispH = this.getHeight(); + int nBgWidth = mbg.getWidth(); + int nBgHeight = mbg.getHeight(); + + m_nScreenWidth = nDispW; + m_nScreenHeight = nDispH; + + if (bitmap == null) { + bitmap = Bitmap.createBitmap(mbg.getWidth(), mbg.getHeight(), Bitmap.Config.RGB_565); + } + + canvas.setDensity(m_nDensity); + bitmap.setDensity(m_nDensity); + Canvas tmpCanvas = new Canvas(bitmap); + drawView(tmpCanvas); + + int nBgW = (int) (fltScale * nBgWidth); + int nBgH = (int) (fltScale * nBgHeight); + Rect src = new Rect(0, 0, nBgWidth, nBgHeight); + Rect dst = new Rect((nDispW - nBgW) / 2, (nDispH - nBgH) / 2, (nDispW + nBgW) / 2, (nDispH + nBgH) / 2); + canvas.drawBitmap(bitmap, src, dst, null); + } + + private void drawView(Canvas canvas) { + if (null == canvas) { + return; + } + canvas.drawBitmap(mbg, 0, 0, null); + canvas.drawBitmap(setting, settingX - setting.getWidth(), settingY - setting.getHeight(), null); + //气泡 + if (!m_bW) { + canvas.drawBitmap(water, x - ballR, y - ballR, null); + } else { + if (m_AccX > 3) { + canvas.drawBitmap(water, centerX + (y - centerY) - ballR, centerY - (x - centerX) - ballR, null); + flagBall = true; + } else if (m_AccX < -3) { + canvas.drawBitmap(water, centerX - (y - centerY) - ballR, centerY + (x - centerX) - ballR, null); + flagBall = false; + } else { + if (flagBall) { + canvas.drawBitmap(water, centerX + (y - centerY) - ballR, centerY - (x - centerX) - ballR, null); + } else { + canvas.drawBitmap(water, centerX - (y - centerY) - ballR, centerY + (x - centerX) - ballR, null); + } + } + } + + + //罗盘箭头 + float dirTmp = m_sensorDir; + if (m_bW) { + if (m_AccX > 3) { + m_sensorDir = (m_sensorDir + 90) % 360; + flagDir = true; + } else if (m_AccX < -3) { + m_sensorDir = (m_sensorDir - 90 + 360) % 360; + flagDir = false; + } else { + if (flagDir) { + m_sensorDir = (m_sensorDir + 90) % 360; + } else { + m_sensorDir = (m_sensorDir - 90 + 360) % 360; + } + } + } + canvas.save(); + canvas.translate(centerX, centerY); + int ndir = (int) m_sensorDir; + m_sensorDir = dirTmp; + int delta = ((360 - ndir) - lastDir + 360) % 360; + if (delta > 2) { + if (delta < 180) { + lastDir = (lastDir + 1 + delta / 3) % 360; + } else { + lastDir = (lastDir - 1 - (360 - delta) / 3 + 360) % 360; + } + } + canvas.rotate(lastDir); + canvas.drawBitmap(arrow, (float) -15, (float) (-redR - 45), null); + canvas.restore(); + + //扫描扇形进行旋转 + canvas.save(); + canvas.translate(centerX, centerY); + canvas.rotate((degree += 3) % 360); + canvas.drawBitmap(sector, sx, sy, null); + canvas.restore(); - //扫描扇形进行旋转 - canvas.save(); - canvas.translate(centerX, centerY); - canvas.rotate((degree += 3)%360); - canvas.drawBitmap(sector, sx, sy, null); - canvas.restore(); - // GpsStatus gsv = MainInfo.GetInstance().getNaviControler().GetCurGSV(); - - if(gsv == null){ + + if (gsv == null) { // gsv = CommonController.getInstance().getLocationMgr(mContext).getGpsStatus(gsv); - } - - if (gsv != null) { - Iterable sats = gsv.getSatellites(); - Iterator iter = sats.iterator(); + } - int nMaxNum = gsv.getMaxSatellites(); - if( nMaxNum <= 0) { - return; - } - - mPrns = new int[nMaxNum]; - mElevation = new float[nMaxNum]; - mAzimuth = new float[nMaxNum]; - mSnrs = new float[nMaxNum]; - mX = new float[nMaxNum]; - mY = new float[nMaxNum]; + if (gsv != null) { + Iterable sats = gsv.getSatellites(); + Iterator iter = sats.iterator(); - int count = 0; - mUsedInFixMask = 0; + int nMaxNum = gsv.getMaxSatellites(); + if (nMaxNum <= 0) { + return; + } - while (iter.hasNext()) { - GpsSatellite sat = (GpsSatellite) iter.next(); + mPrns = new int[nMaxNum]; + mElevation = new float[nMaxNum]; + mAzimuth = new float[nMaxNum]; + mSnrs = new float[nMaxNum]; + mX = new float[nMaxNum]; + mY = new float[nMaxNum]; - int mPrn = sat.getPrn(); - float mSnr = sat.getSnr(); - float mElev = sat.getElevation(); - float mAzi = sat.getAzimuth(); - - if (mElev >= 90 || mAzi< 0 || mPrn <= 0 || mSnr < 0) { - continue; - } + int count = 0; + mUsedInFixMask = 0; - mPrns[count] = mPrn; - mSnrs[count] = mSnr; - mElevation[count] = mElev; - mAzimuth[count] = mAzi; + while (iter.hasNext()) { + GpsSatellite sat = (GpsSatellite) iter.next(); - if (sat.usedInFix()) { - mUsedInFixMask += 1; - } + int mPrn = sat.getPrn(); + float mSnr = sat.getSnr(); + float mElev = sat.getElevation(); + float mAzi = sat.getAzimuth(); - mUsedInFixMask <<= 1; - count++; - } + if (mElev >= 90 || mAzi < 0 || mPrn <= 0 || mSnr < 0) { + continue; + } - mSatellites = count; - computeXY(); - } + mPrns[count] = mPrn; + mSnrs[count] = mSnr; + mElevation[count] = mElev; + mAzimuth[count] = mAzi; - final Paint gridPaint = mGridPaint; - final Paint textPaint = mTextPaint; + if (sat.usedInFix()) { + mUsedInFixMask += 1; + } - double scale = radius / 90.0; - - for (int i = 0; i < mSatellites; ++i) { - //屏蔽无效星历 - if (mElevation[i] >= 90 || mAzimuth[i] <= 0) { - continue; - } - double a = mElevation[i] * scale; + mUsedInFixMask <<= 1; + count++; + } - int x = (int) Math.round(centerX + (mX[i] * a) - mBitmapAdjustment); - int y = (int) Math.round(centerY + (mY[i] * a) - mBitmapAdjustment); + mSatellites = count; + computeXY(); + } - if (0 == mUsedInFixMask || mSnrs[i] <= 0) { - //gridPaint.setColor(Color.GRAY); - // 地图上的卫星符号 - canvas.drawBitmap(grayDot, x, y,null); - } else if (0 != (mUsedInFixMask & (1 << (mSatellites - i)))) { - // 可用 - gridPaint.setColor(Color.GREEN); - canvas.drawBitmap(greenDot, x, y,null); - } else { - gridPaint.setColor(Color.YELLOW); - canvas.drawBitmap(yellowDot, x, y,null); - } - } + final Paint gridPaint = mGridPaint; + final Paint textPaint = mTextPaint; - - // * GPS状态: 搜索中 已连接 速度 高程 方向 卫星颗数(有效的) 时间 - final int fill = 18; - float slotWidth = 36; - float barWidth = slotWidth - fill; + double scale = radius / 90.0; - // 宽13 11 间隔 11 - if (gsv != null) { - for (int i = 0; i < mSatellites; ++i) { - if (mSnrs[i] < 0) { - mSnrs[i] = 0; + for (int i = 0; i < mSatellites; ++i) { + //屏蔽无效星历 + if (mElevation[i] >= 90 || mAzimuth[i] <= 0) { + continue; + } + double a = mElevation[i] * scale; + + int x = (int) Math.round(centerX + (mX[i] * a) - mBitmapAdjustment); + int y = (int) Math.round(centerY + (mY[i] * a) - mBitmapAdjustment); + + if (0 == mUsedInFixMask || mSnrs[i] <= 0) { + //gridPaint.setColor(Color.GRAY); + // 地图上的卫星符号 + canvas.drawBitmap(grayDot, x, y, null); + } else if (0 != (mUsedInFixMask & (1 << (mSatellites - i)))) { + // 可用 + gridPaint.setColor(Color.GREEN); + canvas.drawBitmap(greenDot, x, y, null); + } else { + gridPaint.setColor(Color.YELLOW); + canvas.drawBitmap(yellowDot, x, y, null); + } + } + + + // * GPS状态: 搜索中 已连接 速度 高程 方向 卫星颗数(有效的) 时间 + final int fill = 18; + float slotWidth = 36; + float barWidth = slotWidth - fill; + + // 宽13 11 间隔 11 + if (gsv != null) { + for (int i = 0; i < mSatellites; ++i) { + if (mSnrs[i] < 0) { + mSnrs[i] = 0; // MainInfo.GetInstance().LogAdd("GPS: i=" + i + "<0"); - }else if(mSnrs[i] >= 70){ - mSnrs[i] = 70; - } - } - } + } else if (mSnrs[i] >= 70) { + mSnrs[i] = 70; + } + } + } - int mSatellitesInUsed = 0; - - for (int i = 0; i < mSatellites; ++i) { - if (mPrns[i] <= 0 || mSnrs[i] < 0) { - continue; - } - if(mSatellitesInUsed >= MAX_SATS){ - break; - } - if(!m_bW){//竖屏 - mDrawable.setBounds(new Rect(signalX[i],signalTop,signalX[i] + signalWidth,signalBottom)); - mDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT); + int mSatellitesInUsed = 0; - - if (0 == mUsedInFixMask) { - mDrawable.setColor(0xff858585); - } else if (0 != (mUsedInFixMask & (1 << (mSatellites - i)))) { - mDrawable.setColor(0xff7bd497); - } else { - mDrawable.setColor(0xffffa300); - } - mDrawable.draw(canvas); - canvas.drawLine(signalX[i] + signalWidth/2, signalTop, signalX[i] + signalWidth/2, signalBottom - mSnrs[i], blackPaint); - int n = mPrns[i]%100/10; - if(n > 0){ - canvas.drawBitmap(lNumber[n], signalX[i]-12, signalBottom -5,null); - canvas.drawBitmap(lNumber[mPrns[i]%10], signalX[i]-1, signalBottom -5 ,null); - }else{ - canvas.drawBitmap(lNumber[mPrns[i]%10], signalX[i]-8, signalBottom -5 ,null); - } - } else { - mDrawable.setBounds(new Rect(signalBottom,signalX[i],signalTop,signalX[i] + signalWidth)); - mDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT); - mDrawable.draw(canvas); + for (int i = 0; i < mSatellites; ++i) { + if (mPrns[i] <= 0 || mSnrs[i] < 0) { + continue; + } + if (mSatellitesInUsed >= MAX_SATS) { + break; + } + if (!m_bW) {//竖屏 + mDrawable.setBounds(new Rect(signalX[i], signalTop, signalX[i] + signalWidth, signalBottom)); + mDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT); - canvas.drawLine(signalTop, signalX[i] + signalWidth/2, signalBottom + mSnrs[i],signalX[i] + signalWidth/2, blackPaint); - canvas.drawBitmap(lNumber[mPrns[i]%100/10], signalBottom -38,signalX[i]-10, null); - canvas.drawBitmap(lNumber[mPrns[i]%10], signalBottom-25,signalX[i]-10, null); - } - mSatellitesInUsed++; - - } - //卫星颗数 - if(mSatellites < 10){ - //canvas.drawBitmap(number[0], text1_x, text1_y,null); - canvas.drawBitmap(number[mSatellites], text1_x, text1_y,null); - } - else{ - canvas.drawBitmap(number[mSatellites%100/10], text1_x, text1_y,null); - canvas.drawBitmap(number[mSatellites%10], text1_x+25, text1_y,null); - } - //时间 - Date date = new Date(); - SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); - String s = sdf.format(date); - //System.out.println(s); - canvas.drawBitmap(number[(int)(s.charAt(0)-'0')], text2_x, text2_y,null); - canvas.drawBitmap(number[(int)(s.charAt(1)-'0')], text2_x+20, text2_y,null); - canvas.drawBitmap(dot, text2_x+40, text2_y-2,null); - canvas.drawBitmap(dot, text2_x+40, text2_y+10,null); - canvas.drawBitmap(number[(int)(s.charAt(3)-'0')], text2_x+55, text2_y,null); - canvas.drawBitmap(number[(int)(s.charAt(4)-'0')], text2_x+75, text2_y,null); - canvas.drawBitmap(dot, text2_x+95, text2_y-2,null); - canvas.drawBitmap(dot, text2_x+95, text2_y+10,null); - canvas.drawBitmap(number[(int)(s.charAt(6)-'0')], text2_x+110, text2_y,null); - canvas.drawBitmap(number[(int)(s.charAt(7)-'0')], text2_x+130, text2_y,null); - //方向角 - dirX = ((dirX % 360) + 360) % 360; - s = String.valueOf(dirX); - int startLocation = text3_x; - for(int i = 0 ; i < s.length() ; i++){ - if(s.charAt(i) == '.'){ - canvas.drawBitmap(dot, startLocation, text3_y+12,null); - startLocation +=15 ; - canvas.drawBitmap(number[s.charAt(i+1)-'0'], startLocation, text3_y,null); - break; - } - canvas.drawBitmap(number[s.charAt(i)-'0'], startLocation, text3_y,null); - startLocation +=20 ; - } - //俯仰角 - s = String.valueOf(dirY); - startLocation = text4_x; - for(int i = 0 ; i < s.length() ; i++){ - if(s.charAt(i) == '.'){ - canvas.drawBitmap(dot, startLocation, text4_y+12,null); - startLocation +=15 ; - canvas.drawBitmap(number[s.charAt(i+1)-'0'], startLocation, text4_y,null); - break; - } - canvas.drawBitmap(number[s.charAt(i)-'0'], startLocation, text4_y,null); - startLocation +=20 ; - } - //加速度 - s= String.valueOf(acc); - startLocation = text5_x; - for(int i = 0; i < s.length(); i++ ){ - if(s.charAt(i) == '.'){ - canvas.drawBitmap(dot, startLocation, text5_y+12,null); - startLocation +=15 ; - canvas.drawBitmap(number[s.charAt(i+1)-'0'], startLocation, text5_y,null); - break; - } - canvas.drawBitmap(number[s.charAt(i)-'0'], startLocation, text5_y,null); - startLocation += 20; - } - - //速度 - s= String.valueOf(mSpeed); - startLocation = text6_x - (s.length()-1) * 10; - for(int i = 0; i < s.length() ; i++ ){ - if(s.charAt(i) == '.') { - canvas.drawBitmap(dot, startLocation, text6_y+12,null); - } else { - canvas.drawBitmap(number[s.charAt(i)-'0'], startLocation, text6_y,null); - } - startLocation += 20; - } - } - - private Bitmap decodeResource(Resources resources, int id) { - BitmapFactory.Options opts = new BitmapFactory.Options(); - opts.inTargetDensity = m_nDensity; - return BitmapFactory.decodeResource(resources, id, opts); - } + if (0 == mUsedInFixMask) { + mDrawable.setColor(0xff858585); + } else if (0 != (mUsedInFixMask & (1 << (mSatellites - i)))) { + mDrawable.setColor(0xff7bd497); + } else { + mDrawable.setColor(0xffffa300); + } + mDrawable.draw(canvas); + canvas.drawLine(signalX[i] + signalWidth / 2.0f, signalTop, signalX[i] + signalWidth / 2.0f, signalBottom - mSnrs[i], blackPaint); + int n = mPrns[i] % 100 / 10; + if (n > 0) { + canvas.drawBitmap(lNumber[n], signalX[i] - 12.0f, signalBottom - 5.0f, null); + canvas.drawBitmap(lNumber[mPrns[i] % 10], signalX[i] - 1.0f, signalBottom - 5.0f, null); + } else { + canvas.drawBitmap(lNumber[mPrns[i] % 10], signalX[i] - 8.0f, signalBottom - 5.0f, null); + } + } else { + mDrawable.setBounds(new Rect(signalBottom, signalX[i], signalTop, signalX[i] + signalWidth)); + mDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT); + mDrawable.draw(canvas); - public void update(float[] a, float dir[], float[] la) { - m_AccX = a[0]; - m_AccY = a[1]; - m_sensorDir = dir[0]; - if(delayCount % 20 == 0){ - acc = (float) Math.sqrt(la[0]*la[0] + la[1]*la[1] + la[2]*la[2]); - dirX = dir[0]; - dirY = (-dir[1] + 360) % 360; - delayCount = 0; - } - delayCount++; - if(!start){ - if(count == 0){ - initA[0] = a[0]; - initA[1] = a[1]; - count++; - return; - }else if(count < 10){ - initA[0] = (float) (initA[0] * 0.8 + a[0] * 0.2); - initA[1] = (float) (initA[1] * 0.8 + a[1] * 0.2); - count++; - return; - }else{ - start = true; - lastA[0] = initA[0]; - lastA[1] = initA[1]; - } - } - float mod = (a[0] - lastA[0]) * (a[0] - lastA[0]) + (a[1] - lastA[1]) * (a[1] - lastA[1]); - if(mod > 0.1){ - nx = centerX + (a[0] - initA[0]) * 70; - ny = centerY - (a[1] - initA[1]) * 70; - double d = Math.sqrt((nx - x) * (nx - x) + (ny - y) * (ny - y)); - dx = (nx - x) / d; - dy = (ny - y) / d; - lastA[0] = a[0]- initA[0]; - lastA[1] = a[1]- initA[1]; + canvas.drawLine(signalTop, signalX[i] + signalWidth / 2.0f, signalBottom + mSnrs[i], signalX[i] + signalWidth / 2.0f, blackPaint); + canvas.drawBitmap(lNumber[mPrns[i] % 100 / 10], signalBottom - 38.0f, signalX[i] - 10.0f, null); + canvas.drawBitmap(lNumber[mPrns[i] % 10], signalBottom - 25.0f, signalX[i] - 10.0f, null); + } + mSatellitesInUsed++; - } - float dist = (float) Math.sqrt((x-nx)*(x-nx) + (y-ny)*(y-ny)); - if(dist > 15){ - x += dx * v; - y += dy * v; - } - float temp = (float) Math.sqrt((x-centerX)*(x-centerX) + (y-centerY)*(y-centerY)); - - if(temp > radius){ - x = radius * (x-centerX) / temp; - y = radius * (y-centerY) / temp; - x += centerX; - y += centerY; - } - } - - @Override - public boolean dispatchTouchEvent(MotionEvent ev) { + } - switch( ev.getAction() ) - { - case MotionEvent.ACTION_DOWN: - int m_nX = (int)ev.getX(); - int m_nY = (int)ev.getY(); - int nDisToCenter =(int) Math.sqrt((m_nScreenWidth/2 - m_nX) * (m_nScreenWidth/2 - m_nX) + (m_nScreenHeight/2 - m_nY) * (m_nScreenHeight/2 - m_nY)); - if(nDisToCenter < radius){ - x = centerX; - y = centerY; - initA[0] = m_AccX; - initA[1] = m_AccY; - } - int nBgW = (int)(fltScale * mbg.getWidth()); - int nBgH = (int)(fltScale * mbg.getHeight()); - float x = (m_nX) / fltScale - (this.getWidth() - nBgW)/2; - float y = (m_nY ) / fltScale -(this.getHeight() - nBgH)/2; - if( xsettingX - setting.getWidth() && ysettingY-setting.getHeight()){ - this.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); + //卫星颗数 + if (mSatellites < 10) { + //canvas.drawBitmap(number[0], text1_x, text1_y,null); + canvas.drawBitmap(number[mSatellites], text1_x, text1_y, null); + } else { + canvas.drawBitmap(number[mSatellites % 100 / 10], text1_x, text1_y, null); + canvas.drawBitmap(number[mSatellites % 10], text1_x + 25.0f, text1_y, null); + } + //时间 + Date date = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); + String s = sdf.format(date); + //System.out.println(s); + canvas.drawBitmap(number[s.charAt(0) - '0'], text2_x, text2_y, null); + canvas.drawBitmap(number[s.charAt(1) - '0'], text2_x + 20.0f, text2_y, null); + canvas.drawBitmap(dot, text2_x + 40.0f, text2_y - 2.0f, null); + canvas.drawBitmap(dot, text2_x + 40.0f, text2_y + 10.0f, null); + canvas.drawBitmap(number[s.charAt(3) - '0'], text2_x + 55.0f, text2_y, null); + canvas.drawBitmap(number[s.charAt(4) - '0'], text2_x + 75.0f, text2_y, null); + canvas.drawBitmap(dot, text2_x + 95.0f, text2_y - 2.0f, null); + canvas.drawBitmap(dot, text2_x + 95.0f, text2_y + 10.0f, null); + canvas.drawBitmap(number[s.charAt(6) - '0'], text2_x + 110.0f, text2_y, null); + canvas.drawBitmap(number[s.charAt(7) - '0'], text2_x + 130.0f, text2_y, null); + //方向角 + dirX = ((dirX % 360) + 360) % 360; + s = String.valueOf(dirX); + int startLocation = text3_x; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '.') { + canvas.drawBitmap(dot, startLocation, text3_y + 12.0f, null); + startLocation += 15; + canvas.drawBitmap(number[s.charAt(i + 1) - '0'], startLocation, text3_y, null); + break; + } + canvas.drawBitmap(number[s.charAt(i) - '0'], startLocation, text3_y, null); + startLocation += 20; + } + //俯仰角 + s = String.valueOf(dirY); + startLocation = text4_x; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '.') { + canvas.drawBitmap(dot, startLocation, text4_y + 12.0f, null); + startLocation += 15; + canvas.drawBitmap(number[s.charAt(i + 1) - '0'], startLocation, text4_y, null); + break; + } + canvas.drawBitmap(number[s.charAt(i) - '0'], startLocation, text4_y, null); + startLocation += 20; + } + //加速度 + s = String.valueOf(acc); + startLocation = text5_x; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '.') { + canvas.drawBitmap(dot, startLocation, text5_y + 12.0f, null); + startLocation += 15; + canvas.drawBitmap(number[s.charAt(i + 1) - '0'], startLocation, text5_y, null); + break; + } + canvas.drawBitmap(number[s.charAt(i) - '0'], startLocation, text5_y, null); + startLocation += 20; + } + + //速度 + s = String.valueOf(mSpeed); + startLocation = text6_x - (s.length() - 1) * 10; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '.') { + canvas.drawBitmap(dot, startLocation, text6_y + 12.0f, null); + } else { + canvas.drawBitmap(number[s.charAt(i) - '0'], startLocation, text6_y, null); + } + startLocation += 20; + } + } + + private Bitmap decodeResource(Resources resources, int id) { + BitmapFactory.Options opts = new BitmapFactory.Options(); + opts.inTargetDensity = m_nDensity; + return BitmapFactory.decodeResource(resources, id, opts); + } + + public void update(float[] a, float[] dir, float[] la) { + m_AccX = a[0]; + m_AccY = a[1]; + m_sensorDir = dir[0]; + if (delayCount % 20 == 0) { + acc = (float) Math.sqrt(la[0] * la[0] + la[1] * la[1] + la[2] * la[2]); + dirX = dir[0]; + dirY = (-dir[1] + 360) % 360; + delayCount = 0; + } + delayCount++; + if (!start) { + if (count == 0) { + initA[0] = a[0]; + initA[1] = a[1]; + count++; + return; + } else if (count < 10) { + initA[0] = (float) (initA[0] * 0.8 + a[0] * 0.2); + initA[1] = (float) (initA[1] * 0.8 + a[1] * 0.2); + count++; + return; + } else { + start = true; + lastA[0] = initA[0]; + lastA[1] = initA[1]; + } + } + float mod = (a[0] - lastA[0]) * (a[0] - lastA[0]) + (a[1] - lastA[1]) * (a[1] - lastA[1]); + if (mod > 0.1) { + nx = centerX + (a[0] - initA[0]) * 70; + ny = centerY - (a[1] - initA[1]) * 70; + double d = Math.sqrt((nx - x) * (nx - x) + (ny - y) * (ny - y)); + dx = (nx - x) / d; + dy = (ny - y) / d; + lastA[0] = a[0] - initA[0]; + lastA[1] = a[1] - initA[1]; + + } + float dist = (float) Math.sqrt((x - nx) * (x - nx) + (y - ny) * (y - ny)); + if (dist > 15) { + x += dx * v; + y += dy * v; + } + float temp = (float) Math.sqrt((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY)); + + if (temp > radius) { + x = radius * (x - centerX) / temp; + y = radius * (y - centerY) / temp; + x += centerX; + y += centerY; + } + } + + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + + switch (ev.getAction()) { + case MotionEvent.ACTION_DOWN: + int m_nX = (int) ev.getX(); + int m_nY = (int) ev.getY(); + int nDisToCenter = (int) Math.sqrt((m_nScreenWidth / 2.0 - m_nX) * (m_nScreenWidth / 2.0 - m_nX) + (m_nScreenHeight / 2.0 - m_nY) * (m_nScreenHeight / 2.0 - m_nY)); + if (nDisToCenter < radius) { + x = centerX; + y = centerY; + initA[0] = m_AccX; + initA[1] = m_AccY; + } + int nBgW = (int) (fltScale * mbg.getWidth()); + int nBgH = (int) (fltScale * mbg.getHeight()); + float x = (m_nX) / fltScale - (this.getWidth() - nBgW) / 2.0f; + float y = (m_nY) / fltScale - (this.getHeight() - nBgH) / 2.0f; + if (x < settingX && x > settingX - setting.getWidth() && y < settingY && y > settingY - setting.getHeight()) { + this.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); // MainInfo.GetInstance().getNaviControler().removeDialog(DialogManager.DIALOG_GPS_TEST_MAIN); // MainInfo.GetInstance().getNaviControler().showDialog(DialogManager.DIALOG_GPS_TEST_MAIN); // MainInfo.GetInstance().getAppInfo().addActionInfo("NaviControler", "gpstest", null); - } - break; + } + break; - case MotionEvent.ACTION_UP: - break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_MOVE: + break; + } + return true; + } + + public int getGPSSatellites() { + return mSatellites; + } - case MotionEvent.ACTION_MOVE: - break; - } - return true; - } - - public int getGPSSatellites() { - return mSatellites; - } - } diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/use/Clerk.kt b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/use/Clerk.kt index 4b51a128da..9b3facb18b 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/use/Clerk.kt +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/use/Clerk.kt @@ -38,8 +38,8 @@ class Clerk(private val mMapController: IMapController?) { } job?.cancel() job = mMapController?.getDemaningScope()?.launch(Dispatchers.IO) { - var className: String = "" - var methodName: String = "" + var className = "" + var methodName = "" try { className = Thread.currentThread().stackTrace[3].className methodName = Thread.currentThread().stackTrace[3].methodName @@ -56,8 +56,8 @@ class Clerk(private val mMapController: IMapController?) { } job?.cancel() job = mMapController?.getDemaningScope()?.launch(Dispatchers.IO) { - var className: String = "" - var methodName: String = "" + var className = "" + var methodName = "" try { className = Thread.currentThread().stackTrace[3].className methodName = Thread.currentThread().stackTrace[3].methodName @@ -79,7 +79,7 @@ class Clerk(private val mMapController: IMapController?) { if(CompileConfig.DEBUG){ Log.i(TAG, "add: ${System.currentTimeMillis()}-$key") } - var stringBuffer = cacheMap.get(key) + var stringBuffer = cacheMap[key] if(stringBuffer == null){ stringBuffer = StringBuffer() } @@ -155,29 +155,34 @@ class Clerk(private val mMapController: IMapController?) { uploadJob?.cancel() uploadJob = scope?.launch(Dispatchers.IO) { val path = Recorder.getLogDirectory(TAG) - val file = File(path) - if(!file.isDirectory){ - return@launch - } - val firstlist = file.list() - for(p in firstlist){ - val f = File(p) - if(!f.isDirectory){ - break + path?.let { + val file = File(it) + if(!file.isDirectory){ + return@launch } - val secondlist = f.list() - for(child in secondlist){ - val childFile = File(child) - upload(childFile) + val firstList = file.list() + firstList?.let { + for(p in firstList){ + val f = File(p) + if(!f.isDirectory){ + break + } + val secondList = f.list() + secondList?.let { + for(child in secondList){ + val childFile = File(child) + upload(childFile) + } + } + } } } - } } private suspend fun upload(file:File){ - return - val content = file.readText() +// return +// val content = file.readText() // repository.uploadLogInfo(content) } diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/AMapUtils.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/AMapUtils.java index 7020c5d097..aee75434eb 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/AMapUtils.java +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/AMapUtils.java @@ -53,7 +53,7 @@ public class AMapUtils { var29[0] = var24 * var22; var29[1] = var24 * var18; var29[2] = var20; - return (float)(Math.asin(Math.sqrt((var28[0] - var29[0]) * (var28[0] - var29[0]) + (var28[1] - var29[1]) * (var28[1] - var29[1]) + (var28[2] - var29[2]) * (var28[2] - var29[2])) / 2.0D) * 1.27420015798544E7D); + return (float) (Math.asin(Math.sqrt((var28[0] - var29[0]) * (var28[0] - var29[0]) + (var28[1] - var29[1]) * (var28[1] - var29[1]) + (var28[2] - var29[2]) * (var28[2] - var29[2])) / 2.0D) * 1.27420015798544E7D); } catch (Throwable var26) { var26.printStackTrace(); return 0.0F; @@ -83,8 +83,6 @@ public class AMapUtils { /** * 是否有GPS - * @param context - * @return */ public static boolean hasGPSDevice(Context context) { final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); @@ -92,10 +90,7 @@ public class AMapUtils { return false; } final List providers = mgr.getAllProviders(); - if (providers == null) { - return false; - } - return providers.contains(LocationManager.GPS_PROVIDER); + return providers != null && providers.contains(LocationManager.GPS_PROVIDER); } } \ No newline at end of file diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/MainInfo.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/MainInfo.java index 130e91f0ac..540f62aa69 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/MainInfo.java +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/MainInfo.java @@ -7,7 +7,7 @@ import java.text.SimpleDateFormat; import java.util.Date; public class MainInfo { - private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); + private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); private static MainInfo m_hinst = null; private boolean mbUserLog = true; private static boolean mbDebug = false; @@ -33,11 +33,9 @@ public class MainInfo { if (null == dir) { return; } - try { - FileWriter fw = new FileWriter((dir + "log.txt"), true); + try(FileWriter fw = new FileWriter((dir + "log.txt"), true)) { String date = dateFormat.format(new Date()); fw.write(date + " " + log + "\r\n"); - fw.close(); } catch (Exception ex) { } } @@ -50,10 +48,8 @@ public class MainInfo { if (null == dir) { return; } - try { - FileWriter fw = new FileWriter((dir + "log.txt"), true); + try(FileWriter fw = new FileWriter((dir + "log.txt"), true)) { e.printStackTrace(new PrintWriter(fw)); - fw.close(); } catch (Exception ex) { } } diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/PubFunction.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/PubFunction.java index 87c6de7251..1432d9e438 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/PubFunction.java +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/PubFunction.java @@ -65,7 +65,7 @@ public class PubFunction */ public static double GetLineAngle(int nX1, int nY1, int nX2, int nY2) { - return getAngleToNorth((nX2 - nX1)/5, (nY2 - nY1)/4); + return getAngleToNorth((nX2 - nX1)/5.0f, (nY2 - nY1)/4.0f); } } diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/data/MapDataApi.kt b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/data/MapDataApi.kt index 2f9562607d..745272b89b 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/data/MapDataApi.kt +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/data/MapDataApi.kt @@ -64,21 +64,21 @@ object MapDataApi { * @return */ fun isServiceRunning(context: Context, ServiceName: String): Boolean { - if (true) { - return false - } - if (TextUtils.isEmpty(ServiceName)) { - return false - } - val myManager = context - .getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager - val runningServices = myManager - .getRunningServices(50) as ArrayList - for (info in runningServices) { - if (info.service.className == ServiceName) { - return true - } - } +// if (true) { +// return false +// } +// if (TextUtils.isEmpty(ServiceName)) { +// return false +// } +// val myManager = context +// .getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager +// val runningServices = myManager +// .getRunningServices(50) as ArrayList +// for (info in runningServices) { +// if (info.service.className == ServiceName) { +// return true +// } +// } return false } diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/dialog/BlurView.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/dialog/BlurView.java index 8eff359642..e5f7d06e6f 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/dialog/BlurView.java +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/dialog/BlurView.java @@ -336,10 +336,6 @@ public class BlurView extends View { /** * Custom draw the blurred bitmap and color to define your own shape - * - * @param canvas - * @param blurredBitmap - * @param overlayColor */ protected void drawBlurredBitmap(Canvas canvas, Bitmap blurredBitmap, int overlayColor) { if (blurredBitmap != null) { @@ -371,16 +367,16 @@ public class BlurView extends View { private static class StopException extends RuntimeException { } - private static StopException STOP_EXCEPTION = new StopException(); + private static final StopException STOP_EXCEPTION = new StopException(); - static { +// static { // try { // BlurView.class.getClassLoader().loadClass("androidx.renderscript.RenderScript"); // } catch (ClassNotFoundException e) { // throw new RuntimeException("\n错误!\nRenderScript支持库未启用,要启用模糊效果,请在您的app的Gradle配置文件中添加以下语句:" + // "\nandroid { \n...\n defaultConfig { \n ...\n renderscriptTargetApi 19 \n renderscriptSupportModeEnabled true \n }\n}"); // } - } +// } // android:debuggable="true" in AndroidManifest.xml (auto set by build tool) static Boolean DEBUG = null; @@ -389,6 +385,6 @@ public class BlurView extends View { if (DEBUG == null && ctx != null) { DEBUG = (ctx.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; } - return DEBUG.equals(Boolean.TRUE); + return DEBUG != null && DEBUG.equals(Boolean.TRUE); } } \ No newline at end of file diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/Marker.kt b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/Marker.kt index 711fe9eee3..ff584aed22 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/Marker.kt +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/Marker.kt @@ -800,7 +800,7 @@ public class Marker(private var markerOptions: MarkerOptions,private var mMapCon mMapController?.getContext()?.let {context-> val markerView = BitmapDescriptorFactory.from3DResource(context, icon) markerView?.let { - MD5Utils.getInstanse() + MD5Utils.getInstance() val anchor3dName = MD5Utils.getMD5String(markerView) if (mMarkerCall?.containMarkerIcon(anchor3dName) == false) { if (CompileConfig.DEBUG) { @@ -830,7 +830,7 @@ public class Marker(private var markerOptions: MarkerOptions,private var mMapCon if (icons != null) { for (icon in icons) { val markerView = icon.getBytes() - MD5Utils.getInstanse() + MD5Utils.getInstance() val markerIconName = MD5Utils.getMD5String(markerView) if (mMarkerCall?.containMarkerIcon(markerIconName) == false) { if (CompileConfig.DEBUG) { diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MarkerController.kt b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MarkerController.kt index 969e547371..3b4dc16aec 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MarkerController.kt +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MarkerController.kt @@ -255,7 +255,7 @@ class MarkerController(mapController: IMapController) : IMarkerController { } val markerView = OperationUtils.fromRawResource(modelRes,mMapController.getContext()) if(markerView != null){ - MD5Utils.getInstanse() + MD5Utils.getInstance() val modelKey = MD5Utils.getMD5String(markerView) mMarkerCall.addMarkerIconCache(modelRes,modelKey) diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MarkerOptions.kt b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MarkerOptions.kt index 6ae7e3beee..9bb2870e28 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MarkerOptions.kt +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MarkerOptions.kt @@ -200,7 +200,7 @@ class MarkerOptions { if(markerInfoView.isEmpty()){ return this } - MD5Utils.getInstanse() + MD5Utils.getInstance() val markerInfoMd5 = MD5Utils.getMD5String(markerInfoView) if(!markerInfoUseCache){ if(!TextUtils.isEmpty(markerInfoName) && !TextUtils.equals(markerInfoMd5,markerInfoName)){ @@ -226,7 +226,7 @@ class MarkerOptions { fun markerIcon(bitmap: Bitmap,mapController: IMapController?): MarkerOptions { val markerBitmap = BitmapDescriptorFactory.fromBitmap(bitmap) val markerView = markerBitmap.getBytes() - MD5Utils.getInstanse() + MD5Utils.getInstance() val markerIconName = MD5Utils.getMD5String(markerView) this.markerIconName = markerIconName this.vrIcon = false @@ -279,7 +279,7 @@ class MarkerOptions { fun markerIcon(markerBitmap: BitmapDescriptor,mapController: IMapController?): MarkerOptions { val markerView = markerBitmap.getBytes() - MD5Utils.getInstanse() + MD5Utils.getInstance() val markerIconName = MD5Utils.getMD5String(markerView) this.markerIconName = markerIconName this.vrIcon = false @@ -306,7 +306,7 @@ class MarkerOptions { mapController?.getContext()?.let { val markerView = BitmapDescriptorFactory.from3DResource(it, icon) markerView?.let { - MD5Utils.getInstanse() + MD5Utils.getInstance() val anchor3dName = MD5Utils.getMD5String(markerView) this.icons.add(anchor3dName) if (mapController.getMarkerCall()?.containMarkerIcon(anchor3dName) == false) { @@ -332,7 +332,7 @@ class MarkerOptions { }else { for (icon in icons as ArrayList ) { val markerView = icon.getBytes() - MD5Utils.getInstanse() + MD5Utils.getInstance() val markerIconName = MD5Utils.getMD5String(markerView) this.icons.add(markerIconName) if (mapController?.getMarkerCall()?.containMarkerIcon(markerIconName) == false) { @@ -372,7 +372,7 @@ class MarkerOptions { mapController?.getContext()?.let { val markerBitmap = BitmapDescriptorFactory.fromResource(it, resId) val markerView = markerBitmap.getBytes() - MD5Utils.getInstanse() + MD5Utils.getInstance() val markerIconName = MD5Utils.getMD5String(markerView) this.markerIconName = markerIconName this.vrIcon = false @@ -402,7 +402,7 @@ class MarkerOptions { } if(markerView != null) { - MD5Utils.getInstanse() + MD5Utils.getInstance() val anchor3dName = MD5Utils.getMD5String(markerView) if (mapController?.getMarkerCall()?.containMarkerIcon(anchor3dName) == false) { @@ -451,7 +451,7 @@ class MarkerOptions { } val markerView = OperationUtils.fromRawResource(resId,mapController?.getContext()) if(markerView != null) { - MD5Utils.getInstanse() + MD5Utils.getInstance() val anchor3dName = MD5Utils.getMD5String(markerView) if (mapController?.getMarkerCall()?.containMarkerIcon(anchor3dName) == false) { diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MultiPointOverlayOptions.kt b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MultiPointOverlayOptions.kt index e66baaef27..fb906bd31f 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MultiPointOverlayOptions.kt +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/marker/MultiPointOverlayOptions.kt @@ -23,7 +23,7 @@ class MultiPointOverlayOptions { mapController?.getContext()?.let { val descriptor = fromResource(it, icon) val markerBytes = descriptor.getBytes() - MD5Utils.getInstanse() + MD5Utils.getInstance() this.markerIconName = MD5Utils.getMD5String(markerBytes) if (mapController.getMarkerCall()?.containMarkerIcon(markerIconName) == false) { if(DEBUG){ diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/tools/MD5Utils.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/tools/MD5Utils.java index a9bb773378..a54e3bce29 100644 --- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/tools/MD5Utils.java +++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/open/tools/MD5Utils.java @@ -8,7 +8,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Utils { - protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + protected static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; protected static MessageDigest messagedigest = null; /** @@ -16,7 +16,7 @@ public class MD5Utils { * *  *                   */ - public static MessageDigest getInstanse() { + public static MessageDigest getInstance() { if (messagedigest == null) { try { @@ -31,11 +31,11 @@ public class MD5Utils { messagedigest.update(bytes); return bufferToHex(messagedigest.digest()); } - public static String bufferToHex(byte bytes[]) { + public static String bufferToHex(byte[] bytes) { return bufferToHex(bytes, 0, bytes.length); } - private static String bufferToHex(byte bytes[], int m, int n) { + private static String bufferToHex(byte[] bytes, int m, int n) { StringBuffer stringbuffer = new StringBuffer(2 * n); int k = m + n; for (int l = m; l < k; l++) { @@ -51,9 +51,12 @@ public class MD5Utils { public static boolean isSameImage(byte[] bytes, Context context){ SharedPrefsMgr mgr = SharedPrefsMgr.getInstance(context); String imageStr = mgr.getString(MARKERIMAGE); - MessageDigest md = MD5Utils.getInstanse(); + MessageDigest md = MD5Utils.getInstance(); StringBuffer buffer = new StringBuffer(); buffer.append(imageStr); + if(md == null){ + return false; + } md.update(bytes); String Md5Str = MD5Utils.bufferToHex(md.digest()); if (imageStr.contains(Md5Str)){ diff --git a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/BaseSDCardHelper.java b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/BaseSDCardHelper.java index 1fdceec991..0a461fc6fd 100644 --- a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/BaseSDCardHelper.java +++ b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/BaseSDCardHelper.java @@ -79,7 +79,9 @@ public class BaseSDCardHelper { e.printStackTrace(); } finally { try { - bos.close(); + if (bos != null) { + bos.close(); + } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -108,7 +110,9 @@ public class BaseSDCardHelper { e.printStackTrace(); } finally { try { - bos.close(); + if (bos != null) { + bos.close(); + } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -134,7 +138,9 @@ public class BaseSDCardHelper { e.printStackTrace(); } finally { try { - bos.close(); + if(bos != null){ + bos.close(); + } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -160,7 +166,9 @@ public class BaseSDCardHelper { e.printStackTrace(); } finally { try { - bos.close(); + if(bos != null){ + bos.close(); + } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -177,9 +185,9 @@ public class BaseSDCardHelper { try { bis = new BufferedInputStream( - new FileInputStream(new File(fileDir))); + new FileInputStream(fileDir)); byte[] buffer = new byte[8 * 1024]; - int c = 0; + int c; while ((c = bis.read(buffer)) != -1) { baos.write(buffer, 0, c); baos.flush(); @@ -237,27 +245,27 @@ public class BaseSDCardHelper { * 删除文件夹 * @param path */ - public static boolean deleteAllFilesOfDir(File path) { + public static boolean deleteAllFilesOfDir(File path) { if (!path.exists()){ return false; } if (path.isFile()) { - path.delete(); - return true; + return path.delete(); } File[] files = path.listFiles(); - for (int i = 0; i < files.length; i++) { - deleteAllFilesOfDir(files[i]); + if(files != null){ + for (File file : files) { + deleteAllFilesOfDir(file); + } } - path.delete(); System.out.println("删除文件夹成功"); - return true; + return path.delete(); } /** * 删除文件夹2 * @param path */ - public static void deleteAllFilesOfDir2(File path) { + public static void deleteAllFilesOfDir2(File path) { if (!path.exists()){ return ; } @@ -266,8 +274,10 @@ public class BaseSDCardHelper { return ; } File[] files = path.listFiles(); - for (int i = 0; i < files.length; i++) { - deleteAllFilesOfDir(files[i]); + if(files != null){ + for (File file : files) { + deleteAllFilesOfDir(file); + } } path.delete(); System.out.println("删除文件夹成功"); diff --git a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/IPCFixationIPHelper.java b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/IPCFixationIPHelper.java index dd289c9562..e50f1ee814 100644 --- a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/IPCFixationIPHelper.java +++ b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/IPCFixationIPHelper.java @@ -91,21 +91,18 @@ public class IPCFixationIPHelper { unavailableCount.set(0); isCallListener.set(false); for (final String temp : ips) { - Runnable runnable = new Runnable() { - @Override - public void run() { - CupidLogUtils.i(TAG, "ip=" + temp); - boolean isAvailable = ping(temp); - if (isAvailable) { - if (!isCallListener.get() && !Thread.currentThread().isInterrupted()) { - isCallListener.set(true); - listener.onAvailableIP(temp); - CupidLogUtils.i(TAG, "可用IP=" + temp); - interrupted(); - } - } else { - allNotAvailable(ips); + Runnable runnable = () -> { + CupidLogUtils.i(TAG, "ip=" + temp); + boolean isAvailable = ping(temp); + if (isAvailable) { + if (!isCallListener.get() && !Thread.currentThread().isInterrupted()) { + isCallListener.set(true); + listener.onAvailableIP(temp); + CupidLogUtils.i(TAG, "可用IP=" + temp); + interrupted(); } + } else { + allNotAvailable(ips); } }; Future future = ThreadPoolManager.getsInstance().submit(runnable); diff --git a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/msg/CarConfigRespMessage.java b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/msg/CarConfigRespMessage.java index 98220d91be..f4a0eafc1c 100644 --- a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/msg/CarConfigRespMessage.java +++ b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/msg/CarConfigRespMessage.java @@ -34,7 +34,7 @@ public class CarConfigRespMessage extends MyAbstractMessageHandler { adasListener.onCarConfigResp(raw.getHeader(), carConfigResp); } AdasChannel.calculateTimeConsumingBusiness("车机基础信息应答", nowTime); - CupidLogUtils.e("车机基础信息应答--->" + carConfigResp.toString()); + CupidLogUtils.e("车机基础信息应答--->" + carConfigResp); } /** diff --git a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/subscribe/SubscribeInterface.java b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/subscribe/SubscribeInterface.java index 2e7dca9179..db142ba712 100644 --- a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/subscribe/SubscribeInterface.java +++ b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/subscribe/SubscribeInterface.java @@ -36,7 +36,6 @@ public class SubscribeInterface { public SubscribeInterface(@NonNull OnSubscribeInterfaceListener listener) { this.listener = listener; - if (listener == null) throw new RuntimeException(); init(); } @@ -62,10 +61,8 @@ public class SubscribeInterface { * @param role 角色 详情参见{@link Constants.TERMINAL_ROLE} * @param type 注册类型 详情参见{@link Constants.SUBSCRIBE_TYPE} * @param messageTypes 要操作的接口 - * @return */ public boolean subscribeInterface(@Define.TerminalRole int role, @Define.SubscribeType int type, @NonNull Set messageTypes) { - if (messageTypes == null) return false; MessagePad.SubscribeDataReq.Builder builder = MessagePad.SubscribeDataReq.newBuilder(); builder.setRole(role).setReqType(type); Map temp = new HashMap<>(); @@ -89,9 +86,7 @@ public class SubscribeInterface { } } } - - - return false; + return isSendSucceed; } /** @@ -103,7 +98,6 @@ public class SubscribeInterface { * @return 是否加入ws发送队列 */ public boolean subscribeInterface(@Define.TerminalRole int role, @Define.SubscribeType int type, @NonNull MessageType messageType) { - if (messageType == null) return false; MessagePad.SubscribeDataReq.Builder builder = MessagePad.SubscribeDataReq.newBuilder(); builder.setRole(role).setReqType(type).addDataTypes(messageType.typeCode.getNumber()); boolean isSendSucceed = listener.onSendSubscribe(builder.build().toByteArray()); @@ -120,7 +114,7 @@ public class SubscribeInterface { subscribedInterface.remove(messageType); } } - return false; + return isSendSucceed; } //根据参数查询是否已订阅 diff --git a/libraries/mogo-map/src/main/java/com/mogo/map/AMapViewWrapper.kt b/libraries/mogo-map/src/main/java/com/mogo/map/AMapViewWrapper.kt index 5ece6c9b4c..d864def996 100644 --- a/libraries/mogo-map/src/main/java/com/mogo/map/AMapViewWrapper.kt +++ b/libraries/mogo-map/src/main/java/com/mogo/map/AMapViewWrapper.kt @@ -171,7 +171,7 @@ class AMapViewWrapper(mMapView: MapAutoView) : IMogoMapView, IMogoMapUIControlle //渲染第一帧 @ChainLog( - linkChainLog = ChainConstant.CHAIN_TYPE_INIT_STATUS, + linkChainLog = ChainConstant.CHAIN_TYPE_STATUS, linkCode = ChainConstant.CHAIN_SOURCE_INIT, nodeAliasCode = ChainConstant.CHAIN_CODE_INIT_ON_MAP_INIT, paramIndexes = [-1] @@ -183,7 +183,7 @@ class AMapViewWrapper(mMapView: MapAutoView) : IMogoMapView, IMogoMapUIControlle //地图视图准备 @ChainLog( - linkChainLog = ChainConstant.CHAIN_TYPE_INIT_STATUS, + linkChainLog = ChainConstant.CHAIN_TYPE_STATUS, linkCode = ChainConstant.CHAIN_SOURCE_INIT, nodeAliasCode = ChainConstant.CHAIN_CODE_INIT_ON_MAP_LOADED, paramIndexes = [-1] diff --git a/libraries/mogo-map/src/main/java/com/mogo/map/location/GDLocationClient.kt b/libraries/mogo-map/src/main/java/com/mogo/map/location/GDLocationClient.kt index dd287023fe..c76c7271f4 100644 --- a/libraries/mogo-map/src/main/java/com/mogo/map/location/GDLocationClient.kt +++ b/libraries/mogo-map/src/main/java/com/mogo/map/location/GDLocationClient.kt @@ -144,7 +144,7 @@ class GDLocationClient private constructor() : AMapLocationListener, } @ChainLog( - linkChainLog = ChainConstant.CHAIN_TYPE_INIT_STATUS, + linkChainLog = ChainConstant.CHAIN_TYPE_STATUS, linkCode = ChainConstant.CHAIN_SOURCE_CLOUD, nodeAliasCode = CHAIN_CODE_HTTP_DNS_CITY_CODE, paramIndexes = [0], diff --git a/tts/tts-pad/src/main/java/com/mogo/tts/pad/PadTTS.java b/tts/tts-pad/src/main/java/com/mogo/tts/pad/PadTTS.java index 4c3e8705cf..18a6f2fd72 100644 --- a/tts/tts-pad/src/main/java/com/mogo/tts/pad/PadTTS.java +++ b/tts/tts-pad/src/main/java/com/mogo/tts/pad/PadTTS.java @@ -68,7 +68,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList private int curTtsLevel = -1; // 由于主动打断不会有回调事件,所以主动打断时清掉map中被打断的text和callback private String curTtsContent = ""; - private LinkedList> linkedList = new LinkedList<>(); + private final LinkedList> linkedList = new LinkedList<>(); public void release() { CallerLogger.d(TAG, "release"); @@ -101,13 +101,13 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList private VoiceClient mVoiceClient; private MogoVoiceManager mogoVoiceManager; // 免唤醒指令 - private Map> mCmdMap = new HashMap<>(); + private final Map> mCmdMap = new HashMap<>(); // 问答指令 - private Map mQAndAMap = new HashMap<>(); + private final Map mQAndAMap = new HashMap<>(); // 单独的语音播放 - private Map mSpeakVoiceMap = new HashMap<>(); + private final Map mSpeakVoiceMap = new HashMap<>(); - private Map mCacheUnWakeupCommands = new ConcurrentHashMap<>(); + private final Map mCacheUnWakeupCommands = new ConcurrentHashMap<>(); private static final String TTS_BACK_RES_ZHILING = "zhilingf_common_back_ce_local.v2.1.0.bin"; private int audioRecorderType = DUILiteConfig.TYPE_COMMON_MIC; @@ -119,7 +119,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList public static final String TTS_BACK_RES_GUODGM = "guodgm_common_back_ce_local.v2.1.0.bin"; private AILocalTTSEngine mEngine; private AILocalTTSIntent mAILocalTTSIntent; - private String[] mBackResBinArray = new String[]{TTS_BACK_RES_ZHILING, TTS_BACK_RES_GUODGM}; + private final String[] mBackResBinArray = new String[]{TTS_BACK_RES_ZHILING, TTS_BACK_RES_GUODGM}; // 单独的语音播放 private boolean mHasAuth; private int retryCount; @@ -277,8 +277,6 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList /** * 是否语音注册成功 - * - * @return */ @Override public boolean hasFlush() { @@ -363,8 +361,6 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList /** * 语音播报 - * - * @param text */ public void speakTTSVoice(String text, IMogoTTSCallback callBack) { if (mEngine != null && mHasAuth) { @@ -376,9 +372,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList public void stopSpeakTts(String text) { if (mEngine != null && mHasAuth) { - if (mSpeakVoiceMap.containsKey(text)) { - mSpeakVoiceMap.remove(text); - } + mSpeakVoiceMap.remove(text); curTtsContent = ""; curTtsLevel = -1; mEngine.stop(); @@ -387,9 +381,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList public void stopTts() { if (mEngine != null && mHasAuth) { - if (mSpeakVoiceMap.containsKey(curTtsContent)) { - mSpeakVoiceMap.remove(curTtsContent); - } + mSpeakVoiceMap.remove(curTtsContent); // tts过程中调用stop不会有回调事件 curTtsContent = ""; curTtsLevel = -1; @@ -399,8 +391,6 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList /** * 语音播报 - * - * @param text */ public void speakTTSVoice(String text) { CallerLogger.d(TAG, "speakTTSVoice"); @@ -493,24 +483,24 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList initFlushStatus(); if (mHasFlush) { mSpeakVoiceMap.put(text, callBack); - VoiceClient.PreemptType preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_NONE; - if (type != null) { - switch (type) { - case PREEMPT_TYPE_NEXT: - preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_NEXT; - break; - case PREEMPT_TYPE_FLUSH: - preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_FLUSH; - break; - case PREEMPT_TYPE_IMMEDIATELY: - preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_IMMEADIATELY; - break; - case PREEMPT_TYPE_IMMEDIATELY_WITHOUT_CANCEL: - preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_IMMEADIATELY_WITHOUT_CANCLE; - break; - } - } speakTTSVoice(text); +// VoiceClient.PreemptType preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_NONE; +// if (type != null) { +// switch (type) { +// case PREEMPT_TYPE_NEXT: +// preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_NEXT; +// break; +// case PREEMPT_TYPE_FLUSH: +// preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_FLUSH; +// break; +// case PREEMPT_TYPE_IMMEDIATELY: +// preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_IMMEADIATELY; +// break; +// case PREEMPT_TYPE_IMMEDIATELY_WITHOUT_CANCEL: +// preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_IMMEADIATELY_WITHOUT_CANCLE; +// break; +// } +// } // mVoiceClient.speakTypeText( text, preemptType ); } } catch (Exception e) { @@ -679,7 +669,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList CallerLogger.d(TAG, "txz is voiceServiceReady"); return true; } - return true; + return false; } public void speakTTSAndDuck(String text) {