模块代码迁移

将foudations包下的mogo-utils模块下的代码迁移到core包下的mogo-core-utils模块下
注:远程依赖库网约车模块目前使用的是foudations包下的mogo-utils模块下Logger,
目前看项目中无该网约车模块功能,暂时注释掉该模块
This commit is contained in:
xuxinchao
2021-12-28 14:52:30 +08:00
parent 4b93315959
commit 8682f9bcb2
379 changed files with 1423 additions and 2705 deletions

View File

@@ -12,6 +12,7 @@ import com.mogo.eagle.core.function.check.net.CheckNetWork.checkNetWork
import com.mogo.eagle.core.function.check.net.CheckResultData
import com.mogo.eagle.core.function.check.view.CheckActivity
import com.mogo.eagle.core.function.check.view.CheckDialog
import com.mogo.eagle.core.utilcode.util.ActivityLifecycleManager
import com.mogo.eagle.core.utilcode.util.ActivityUtils
import com.mogo.eagle.core.utilcode.util.AppUtils
import com.mogo.eagle.core.utilcode.util.LogUtils
@@ -19,7 +20,6 @@ import com.mogo.module.common.MogoApisHandler
import com.mogo.module.service.receiver.MogoReceiver
import com.mogo.service.statusmanager.IMogoStatusChangedListener
import com.mogo.service.statusmanager.StatusDescriptor
import com.mogo.utils.ActivityLifecycleManager
import java.util.concurrent.ConcurrentHashMap
/**

View File

@@ -9,13 +9,13 @@ import com.mogo.commons.AbsMogoApplication
import com.mogo.commons.debug.DebugConfig
import com.mogo.eagle.core.function.call.devatools.CallerDevaToolsListenerManager
import com.mogo.eagle.core.network.NetConfig
import com.mogo.eagle.core.utilcode.mogo.logger.LogLevel
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.eagle.core.utilcode.mogo.toast.TipToast
import com.mogo.eagle.core.utilcode.util.ThreadUtils
import com.mogo.eagle.core.utilcode.util.TimeUtils
import com.mogo.module.common.MogoApisHandler
import com.mogo.service.cloud.socket.IMogoOnMessageListener
import com.mogo.utils.logger.LogLevel
import com.mogo.utils.logger.Logger
import com.zhidao.loglib.bean.RemoteLogPushContent
import com.zhidao.loglib.call.LogInfoManagerFactory
import com.zhidao.loglib.core.ILogListener

View File

@@ -5,8 +5,8 @@ import android.view.View
import com.mogo.eagle.core.function.hmi.notification.enums.SidePattern
import com.mogo.eagle.core.function.hmi.notification.interfaces.OnFloatAnimator
import com.mogo.eagle.core.function.api.hmi.warning.IMoGoWarningStatusListener
import com.mogo.utils.WindowUtils
import com.mogo.utils.logger.Logger
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.eagle.core.utilcode.util.WindowUtils
/**
* @author donghongyu

View File

@@ -12,12 +12,11 @@ import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import com.mogo.eagle.core.function.hmi.R
import com.mogo.eagle.core.function.hmi.notification.anim.AnimatorManager
import com.mogo.eagle.core.function.hmi.notification.enums.ShowPattern
import com.mogo.eagle.core.function.hmi.notification.widget.ParentFrameLayout
import com.mogo.utils.WindowUtils
import com.mogo.utils.logger.Logger
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.eagle.core.utilcode.util.WindowUtils
/**
* @author donghongyu

View File

@@ -7,7 +7,7 @@ import android.view.View
import android.view.WindowManager
import com.mogo.eagle.core.function.hmi.notification.enums.SidePattern
import com.mogo.eagle.core.function.hmi.notification.interfaces.OnFloatAnimator
import com.mogo.utils.WindowUtils
import com.mogo.eagle.core.utilcode.util.WindowUtils
import kotlin.math.min
/**

View File

@@ -4,15 +4,11 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.alibaba.android.arouter.launcher.ARouter
import com.mogo.module.common.enums.EventTypeEnum
import com.mogo.eagle.core.function.hmi.WaringConst
import com.mogo.service.IMogoServiceApis
import com.mogo.eagle.core.data.constants.MogoServicePaths
import com.mogo.eagle.core.data.notice.NoticeNormalData
import com.mogo.eagle.core.function.api.hmi.warning.IMoGoWaringProvider
import com.mogo.eagle.core.function.call.hmi.CallerHmiManager
import com.mogo.eagle.core.utilcode.util.SharedPrefs
import com.mogo.utils.logger.Logger
/**
* 用于普通云公告的测试

View File

@@ -7,8 +7,8 @@ import com.alibaba.android.arouter.launcher.ARouter
import com.mogo.eagle.core.data.constants.MogoServicePaths
import com.mogo.eagle.core.function.call.hmi.CallerHmiManager
import com.mogo.eagle.core.function.hmi.WaringConst
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.service.IMogoServiceApis
import com.mogo.utils.logger.Logger
/**
* V2X 预警广播接收。用于跨应用,跨进程,内部也可以通过这种方式 控制限速标志

View File

@@ -7,8 +7,8 @@ import com.alibaba.android.arouter.launcher.ARouter
import com.mogo.eagle.core.data.constants.MogoServicePaths
import com.mogo.eagle.core.function.call.hmi.CallerHmiManager
import com.mogo.eagle.core.function.hmi.WaringConst
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.service.IMogoServiceApis
import com.mogo.utils.logger.Logger
/**
* V2X 预警广播接收。用于跨应用,跨进程,内部也可以通过这种方式 触发红绿灯场景

View File

@@ -7,9 +7,9 @@ import com.alibaba.android.arouter.launcher.ARouter
import com.mogo.eagle.core.data.constants.MogoServicePaths
import com.mogo.eagle.core.function.call.hmi.CallerHmiManager
import com.mogo.eagle.core.function.hmi.WaringConst
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.module.common.enums.EventTypeEnum
import com.mogo.service.IMogoServiceApis
import com.mogo.utils.logger.Logger
/**
* V2X 预警广播接收。用于跨应用,跨进程,内部也可以通过这种方式弹出预警提示框

View File

@@ -31,10 +31,10 @@ import com.mogo.eagle.core.function.hmi.ui.notice.NoticeNormalBannerView
import com.mogo.eagle.core.function.hmi.ui.setting.DebugSettingView
import com.mogo.eagle.core.function.hmi.ui.tools.AutoPilotAndCheckView
import com.mogo.eagle.core.function.hmi.ui.widget.V2XNotificationView
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.eagle.core.utilcode.util.ThreadUtils
import com.mogo.eagle.core.utilcode.util.ToastUtils
import com.mogo.module.common.enums.EventTypeEnum
import com.mogo.utils.logger.Logger
import kotlinx.android.synthetic.main.fragment_hmi.*
/**

View File

@@ -23,8 +23,8 @@ import com.mogo.cloud.trafficlive.api.MoGoAiCloudTrafficLive
import com.mogo.eagle.core.data.camera.CameraEntity
import com.mogo.eagle.core.function.call.monitor.CallerMonitorManager
import com.mogo.eagle.core.function.hmi.R
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.eagle.core.widget.media.video.SimpleVideoPlayer
import com.mogo.utils.logger.Logger
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.model.VideoOptionModel

View File

@@ -17,10 +17,10 @@ import com.mogo.eagle.core.data.notice.NoticeTrafficStylePushData;
import com.mogo.eagle.core.function.hmi.R;
import com.mogo.eagle.core.function.hmi.WaringConst;
import com.mogo.eagle.core.function.hmi.notification.WarningFloat;
import com.mogo.eagle.core.utilcode.mogo.glide.GlideApp;
import com.mogo.eagle.core.utilcode.mogo.glide.GlideRoundedCornersTransform;
import com.mogo.eagle.core.utilcode.util.BitmapHelper;
import com.mogo.eagle.core.utilcode.util.ThreadUtils;
import com.mogo.utils.BitmapHelper;
import com.mogo.utils.glide.GlideApp;
import com.mogo.utils.glide.GlideRoundedCornersTransform;
/**
* @author liujing

View File

@@ -10,15 +10,15 @@ import android.widget.TextView
import androidx.lifecycle.LifecycleObserver
import com.mogo.eagle.core.data.notice.NoticeNormalData
import com.mogo.eagle.core.function.hmi.R
import com.mogo.eagle.core.utilcode.mogo.glide.GlideApp
import com.mogo.eagle.core.utilcode.mogo.glide.GlideRoundedCornersTransform
import com.mogo.eagle.core.utilcode.util.BitmapHelper
import com.mogo.eagle.core.widget.media.video.NoticeSimpleVideoPlayer
import com.mogo.module.common.MogoApisHandler
import com.mogo.module.common.dialog.BaseFloatDialog
import com.mogo.service.IMogoServiceApis
import com.mogo.service.statusmanager.IMogoStatusChangedListener
import com.mogo.service.statusmanager.StatusDescriptor
import com.mogo.utils.BitmapHelper
import com.mogo.utils.glide.GlideApp
import com.mogo.utils.glide.GlideRoundedCornersTransform
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack
@@ -122,8 +122,10 @@ class NoticeCheckDialog(context: Context) : BaseFloatDialog(context), LifecycleO
pushVideo?.visibility = View.GONE
pushImageView?.visibility = View.VISIBLE
pushImageView?.let {
GlideApp.with(context).load(noticeNormal.imageUrl).optionalTransform(GlideRoundedCornersTransform(
20f, GlideRoundedCornersTransform.CornerType.ALL)).into(it)
GlideApp.with(context).load(noticeNormal.imageUrl).optionalTransform(
GlideRoundedCornersTransform(
20f, GlideRoundedCornersTransform.CornerType.ALL)
).into(it)
}
}

View File

@@ -12,14 +12,12 @@ import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.mogo.eagle.core.data.notice.NoticeNormalData;
import com.mogo.eagle.core.data.notice.NoticeTrafficStyleInfo;
import com.mogo.eagle.core.data.notice.NoticeTrafficStylePushData;
import com.mogo.eagle.core.function.hmi.R;
import com.mogo.eagle.core.function.hmi.WaringConst;
import com.mogo.eagle.core.function.hmi.notification.WarningFloat;
import com.mogo.eagle.core.utilcode.util.SharedPrefs;
import com.mogo.utils.glide.GlideApp;
import com.mogo.utils.glide.GlideRoundedCornersTransform;
import com.mogo.eagle.core.utilcode.mogo.glide.GlideApp;
import com.mogo.eagle.core.utilcode.mogo.glide.GlideRoundedCornersTransform;
/**
* @author lixiaopeng

View File

@@ -22,6 +22,10 @@ import com.mogo.eagle.core.function.api.notice.NoticeNetCallBack;
import com.mogo.eagle.core.function.call.autopilot.CallerAutoPilotManager;
import com.mogo.eagle.core.function.call.notice.CallerNoticeManager;
import com.mogo.eagle.core.function.hmi.R;
import com.mogo.eagle.core.utilcode.mogo.glide.GlideApp;
import com.mogo.eagle.core.utilcode.mogo.glide.GlideRoundedCornersTransform;
import com.mogo.eagle.core.utilcode.util.BitmapHelper;
import com.mogo.eagle.core.utilcode.util.DateTimeUtils;
import com.mogo.eagle.core.widget.media.video.NoticeSimpleSmallVideoPlayer;
import com.mogo.module.common.MogoApisHandler;
import com.mogo.module.common.dialog.BaseFloatDialog;
@@ -29,11 +33,7 @@ import com.mogo.service.IMogoServiceApis;
import com.mogo.service.imageloader.MogoImageView;
import com.mogo.service.statusmanager.IMogoStatusChangedListener;
import com.mogo.service.statusmanager.StatusDescriptor;
import com.mogo.utils.BitmapHelper;
import com.mogo.utils.glide.GlideApp;
import com.mogo.utils.glide.GlideRoundedCornersTransform;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.mogo.utils.DateTimeUtils;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack;
import com.shuyu.gsyvideoplayer.utils.NetworkUtils;

View File

@@ -36,14 +36,9 @@ import com.mogo.eagle.core.function.hmi.R
import com.mogo.eagle.core.network.utils.GsonUtil
import com.mogo.eagle.core.utilcode.mogo.logger.LogLevel
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.eagle.core.utilcode.util.AppUtils
import com.mogo.eagle.core.utilcode.util.GsonUtils
import com.mogo.eagle.core.utilcode.util.LogUtils
import com.mogo.eagle.core.utilcode.util.ToastUtils
import com.mogo.eagle.core.utilcode.mogo.storage.SharedPrefsMgr
import com.mogo.eagle.core.utilcode.util.*
import com.mogo.map.MogoMap
import com.mogo.utils.DeviceIdUtils
import com.mogo.utils.UiThreadHandler
import com.mogo.utils.storage.SharedPrefsMgr
import kotlinx.android.synthetic.main.view_debug_setting.view.*
/**
@@ -279,13 +274,11 @@ class DebugSettingView @JvmOverloads constructor(
if (isChecked) {
LogUtils.getConfig().isLogSwitch = false
Logger.init(LogLevel.OFF)
com.mogo.utils.logger.Logger.init(com.mogo.utils.logger.LogLevel.OFF)
com.elegant.log.simplelog.Logger.init(com.elegant.log.simplelog.LogLevel.OFF)
com.zhidao.account.sdk.utils.Logger.init(false)
} else {
LogUtils.getConfig().isLogSwitch = true
Logger.init(LogLevel.DEBUG)
com.mogo.utils.logger.Logger.init(com.mogo.utils.logger.LogLevel.DEBUG)
com.elegant.log.simplelog.Logger.init(com.elegant.log.simplelog.LogLevel.DEBUG)
com.zhidao.account.sdk.utils.Logger.init(true)
}

View File

@@ -16,8 +16,8 @@ import com.mogo.eagle.core.function.call.hmi.CallerHmiListenerManager
import com.mogo.eagle.core.function.hmi.R
import com.mogo.eagle.core.utilcode.util.LogUtils
import com.mogo.eagle.core.utilcode.util.ToastUtils
import com.mogo.eagle.core.utilcode.util.UiThreadHandler
import com.mogo.module.common.MogoApisHandler
import com.mogo.utils.UiThreadHandler
import kotlinx.android.synthetic.main.view_autopilot_status.view.*
/**

View File

@@ -1,28 +1,18 @@
package com.mogo.eagle.core.function.hmi.ui.widget
import android.animation.Animator
import android.content.Context
import android.graphics.Color
import android.location.Location
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.view.animation.OvershootInterpolator
import android.widget.FrameLayout
import com.alibaba.android.arouter.launcher.ARouter
import com.mogo.eagle.core.data.constants.MogoServicePaths
import com.mogo.eagle.core.data.map.MogoLatLng
import com.mogo.eagle.core.function.hmi.R
import com.mogo.eagle.core.function.hmi.notification.WarningFloat
import com.mogo.eagle.core.function.hmi.notification.anim.DefaultAnimator
import com.mogo.eagle.core.function.hmi.notification.enums.SidePattern
import com.mogo.eagle.core.function.hmi.ui.setting.DebugSettingView
import com.mogo.eagle.core.utilcode.util.UiThreadHandler
import com.mogo.map.navi.IMogoCarLocationChangedListener2
import com.mogo.service.IMogoServiceApis
import com.mogo.service.statusmanager.StatusDescriptor
import com.mogo.utils.UiThreadHandler
import java.util.*
/**

View File

@@ -6,7 +6,7 @@ import android.view.LayoutInflater
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import com.mogo.eagle.core.function.hmi.R
import com.mogo.utils.UiThreadHandler
import com.mogo.eagle.core.utilcode.util.UiThreadHandler
import kotlinx.android.synthetic.main.view_traffic_light_vr.view.*
/**

View File

@@ -9,7 +9,7 @@ import androidx.annotation.Nullable
import androidx.annotation.StringRes
import androidx.constraintlayout.widget.ConstraintLayout
import com.mogo.eagle.core.function.hmi.R
import com.mogo.utils.UiThreadHandler
import com.mogo.eagle.core.utilcode.util.UiThreadHandler
import kotlinx.android.synthetic.main.notification_v2x_msg_vr.view.*
/**

View File

@@ -7,8 +7,8 @@ import android.view.View
import android.widget.RelativeLayout
import com.mogo.eagle.core.data.enums.WarningDirectionEnum
import com.mogo.eagle.core.function.hmi.R
import com.mogo.utils.UiThreadHandler
import com.mogo.utils.logger.Logger
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.eagle.core.utilcode.util.UiThreadHandler
import kotlinx.android.synthetic.main.module_hmi_warning_v2x.view.*
/**

View File

@@ -5,7 +5,7 @@ import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import com.mogo.eagle.core.function.hmi.R
import com.mogo.utils.UiThreadHandler
import com.mogo.eagle.core.utilcode.util.UiThreadHandler
import kotlinx.android.synthetic.main.view_vip_identification.view.*
/**

View File

@@ -12,12 +12,12 @@ import androidx.annotation.Nullable;
import com.alibaba.android.arouter.launcher.ARouter;
import com.mogo.commons.debug.DebugConfig;
import com.mogo.eagle.core.function.api.base.IMoGoFunctionProvider;
import com.mogo.eagle.core.utilcode.mogo.logger.Logger;
import com.mogo.eagle.core.utilcode.util.ActivityLifecycleManager;
import com.mogo.map.uicontroller.EnumMapUI;
import com.mogo.module.main.MainActivity;
import com.mogo.service.intent.IMogoIntentListener;
import com.mogo.service.statusmanager.StatusDescriptor;
import com.mogo.utils.ActivityLifecycleManager;
import com.mogo.utils.logger.Logger;
/**
* 针对作为Launcher的情况做个性化操作
@@ -79,7 +79,7 @@ public class MainLauncherActivity extends MainActivity implements IMogoIntentLis
protected void loadOthersModules() {
super.loadOthersModules();
Logger.d(TAG, "loadOthersModules");
loadOCHModule();
// loadOCHModule();
}
/**

View File

@@ -20,7 +20,10 @@ import com.mogo.eagle.core.data.constants.MogoServicePaths;
import com.mogo.eagle.core.data.map.MogoLocation;
import com.mogo.eagle.core.function.notice.PushUIConstants;
import com.mogo.eagle.core.utilcode.mogo.AppLaunchTimeUtils;
import com.mogo.eagle.core.utilcode.mogo.logger.Logger;
import com.mogo.eagle.core.utilcode.mogo.storage.SharedPrefsMgr;
import com.mogo.eagle.core.utilcode.util.DeviceUtils;
import com.mogo.eagle.core.utilcode.util.ProcessUtils;
import com.mogo.map.MapApiPath;
import com.mogo.module.carchatting.card.CallChatConstant;
import com.mogo.module.common.MogoApisHandler;
@@ -34,9 +37,6 @@ import com.mogo.module.v2x.V2XConst;
import com.mogo.service.IMogoServiceApis;
import com.mogo.service.cloud.socket.IMogoLifecycleListener;
import com.mogo.test.crashreport.upgrade.UpgradeReportConstants;
import com.mogo.utils.ProcessUtils;
import com.mogo.utils.logger.Logger;
import com.mogo.utils.storage.SharedPrefsMgr;
import com.zhidao.boot.persistent.lib.PersistentManager;
import com.zhidao.support.obu.ami.AmiClientManager;
import com.zhjt.service.chain.core.ChainTraceStarter;

View File

@@ -6,11 +6,10 @@ import android.os.Looper
import android.os.Message
import com.mogo.eagle.core.data.camera.*
import com.mogo.eagle.core.function.call.hmi.CallerHmiManager
import com.mogo.eagle.core.function.call.map.CallerMapLocationListenerManager
import com.mogo.eagle.core.function.monitoring.net.CameraListServices
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.module.common.MogoApisHandler
import com.mogo.module.common.constants.HostConst
import com.mogo.utils.logger.Logger
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

View File

@@ -68,7 +68,6 @@ dependencies {
implementation rootProject.ext.dependencies.mogo_core_res
implementation rootProject.ext.dependencies.mogo_core_network
implementation rootProject.ext.dependencies.mogo_core_function_call
implementation rootProject.ext.dependencies.mogoutils
} else {
implementation project(":foudations:mogo-commons")
implementation project(':services:mogo-service-api')
@@ -79,7 +78,6 @@ dependencies {
implementation project(':core:mogo-core-res')
implementation project(':core:mogo-core-network')
implementation project(':core:mogo-core-function-call')
implementation project(':foudations:mogo-utils')
}
}

View File

@@ -7,9 +7,9 @@ import com.mogo.eagle.core.data.notice.NoticeNormalData;
import com.mogo.eagle.core.data.notice.NoticeTrafficStylePushData;
import com.mogo.eagle.core.function.call.hmi.CallerHmiManager;
import com.mogo.eagle.core.network.utils.GsonUtil;
import com.mogo.eagle.core.utilcode.mogo.logger.Logger;
import com.mogo.module.common.MogoApisHandler;
import com.mogo.service.cloud.socket.IMogoOnMessageListener;
import com.mogo.utils.logger.Logger;
/**
* @author Jing

View File

@@ -15,6 +15,7 @@ import com.mogo.eagle.core.function.notice.utils.AnimatorUtilsKt;
import com.mogo.eagle.core.function.notice.view.GlobalToolsKt;
import com.mogo.eagle.core.function.notice.view.PushItemAnimator;
import com.mogo.eagle.core.function.notice.view.SwipeItemLayout;
import com.mogo.eagle.core.utilcode.util.UiThreadHandler;
import com.mogo.module.common.view.OnPreventFastClickListener;
import com.mogo.eagle.core.function.notice.Config;
import com.mogo.eagle.core.function.notice.adapter.PushMessageAdapter;
@@ -23,7 +24,6 @@ import com.mogo.eagle.core.function.notice.repository.PushRepository;
import com.mogo.eagle.core.function.notice.utils.HandlerUtils;
import com.mogo.eagle.core.function.notice.viewmodel.MessageViewModel;
import com.mogo.service.statusmanager.IMogoMsgCenterListener;
import com.mogo.utils.UiThreadHandler;
import org.jetbrains.annotations.NotNull;

View File

@@ -12,7 +12,7 @@ import com.mogo.eagle.core.data.notice.NoticeTrafficStyleInfo;
import com.mogo.eagle.core.function.api.notice.NoticeNetCallBack;
import com.mogo.eagle.core.network.utils.GsonUtil;
import com.mogo.utils.logger.Logger;
import com.mogo.eagle.core.utilcode.mogo.logger.Logger;
import java.util.HashMap;
import java.util.Map;

View File

@@ -11,9 +11,9 @@ import com.mogo.eagle.core.function.notice.model.PushBean
import com.mogo.eagle.core.function.notice.utils.HandlerUtils
import com.mogo.eagle.core.function.notice.view.getApis
import com.mogo.eagle.core.function.notice.viewmodel.PushViewModel
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.service.statusmanager.IMogoStatusChangedListener
import com.mogo.service.statusmanager.StatusDescriptor
import com.mogo.utils.logger.Logger
import java.util.*
import kotlin.collections.HashSet

View File

@@ -6,7 +6,7 @@ import android.content.Intent
import android.util.Log
import com.mogo.eagle.core.data.notice.NoticeTrafficStylePushData
import com.mogo.eagle.core.function.call.hmi.CallerHmiManager
import com.mogo.utils.logger.Logger
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
/**
* @author Jing

View File

@@ -4,7 +4,7 @@ import android.view.View
import android.view.ViewGroup
import androidx.core.view.get
import androidx.core.view.isNotEmpty
import com.mogo.utils.logger.Logger
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
const val TAG: String = "AnimatorUtils.kt"

View File

@@ -17,11 +17,11 @@ import com.mogo.eagle.core.function.notice.utils.AnalyticsUtils
import com.mogo.eagle.core.function.notice.utils.stringConverterBitmap
import com.mogo.eagle.core.function.notice.view.roundimage.RoundedImageView
import com.mogo.eagle.core.function.notice.viewmodel.PushViewModel
import com.mogo.eagle.core.utilcode.mogo.glide.GlideApp
import com.mogo.eagle.core.utilcode.util.ThreadPoolService
import com.mogo.eagle.core.utilcode.util.UiThreadHandler
import com.mogo.service.windowview.IMogoTopViewManager
import com.mogo.service.windowview.IMogoTopViewStatusListener
import com.mogo.utils.ThreadPoolService
import com.mogo.utils.UiThreadHandler
import com.mogo.utils.glide.GlideApp
class FloatView constructor(
private val pushViewModel: PushViewModel,

View File

@@ -5,8 +5,8 @@ import com.alibaba.android.arouter.facade.annotation.Route
import com.mogo.eagle.core.data.constants.MoGoConfig
import com.mogo.eagle.core.data.constants.MogoServicePaths
import com.mogo.eagle.core.function.api.obu.IMoGoObuProvider
import com.mogo.eagle.core.utilcode.mogo.storage.SharedPrefsMgr
import com.mogo.eagle.core.utilcode.util.LogUtils
import com.mogo.utils.storage.SharedPrefsMgr
/**
* @author xiaoyuzhou

View File

@@ -10,12 +10,12 @@ import com.mogo.eagle.core.function.call.hmi.CallerHmiManager
import com.mogo.eagle.core.function.call.obu.CallerObuListenerManager
import com.mogo.eagle.core.function.obu.mogo.utils.TrafficDataConvertUtils
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.eagle.core.utilcode.mogo.storage.SharedPrefsMgr
import com.mogo.module.common.datacenter.SnapshotLocationDataCenter
import com.mogo.module.common.drawer.TrafficMarkerDrawer
import com.mogo.module.common.enums.EventTypeEnum
import com.mogo.service.IMogoServiceApis
import com.mogo.service.map.IMogoMapService
import com.mogo.utils.storage.SharedPrefsMgr
import com.zhidao.support.obu.MogoObuManager
import com.zhidao.support.obu.OnMogoObuListener
import com.zhidao.support.obu.constants.ObuConstants

View File

@@ -35,10 +35,10 @@ import com.mogo.eagle.core.function.api.map.listener.IMoGoMapLocationListener;
import com.mogo.eagle.core.function.call.map.CallerMapLocationListenerManager;
import com.mogo.eagle.core.function.smp.utils.MapAssetStyleUtils;
import com.mogo.eagle.core.function.smp.view.ISmallMapDirectionView;
import com.mogo.eagle.core.utilcode.mogo.logger.Logger;
import com.mogo.eagle.core.widget.RoundLayout;
import com.mogo.module.common.MogoApisHandler;
import com.mogo.module.common.utils.DrivingDirectionUtils;
import com.mogo.utils.logger.Logger;
import java.util.ArrayList;
import java.util.List;

View File

@@ -18,9 +18,9 @@ import com.mogo.eagle.core.function.api.autopilot.IMoGoAutopilotPlanningListener
import com.mogo.eagle.core.function.api.autopilot.IMoGoAutopilotStatusListener;
import com.mogo.eagle.core.function.api.map.smp.IMogoSmallMapProvider;
import com.mogo.eagle.core.function.call.autopilot.CallerAutopilotPlanningListenerManager;
import com.mogo.eagle.core.utilcode.util.UiThreadHandler;
import com.mogo.module.common.MogoApisHandler;
import com.mogo.service.adas.IMogoAdasOCHCallback;
import com.mogo.utils.UiThreadHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

View File

@@ -10,11 +10,11 @@ import com.mogo.eagle.core.function.call.hmi.CallerHmiManager
import com.mogo.eagle.core.function.call.trafficlight.CallTrafficLightListenerManager
import com.mogo.eagle.core.function.call.vip.CallVipSetListenerManager
import com.mogo.eagle.core.function.v2x.vip.VipCarManager
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.eagle.core.utilcode.util.ThreadUtils
import com.mogo.map.navi.IMogoCarLocationChangedListener2
import com.mogo.module.common.MogoApisHandler
import com.mogo.module.common.enums.EventTypeEnum
import com.mogo.utils.logger.Logger
import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.floor

View File

@@ -5,12 +5,10 @@ import android.location.Location;
import com.mogo.eagle.core.data.map.MogoLatLng;
import com.mogo.eagle.core.function.call.hmi.CallerHmiManager;
import com.mogo.eagle.core.utilcode.util.UiThreadHandler;
import com.mogo.map.navi.IMogoCarLocationChangedListener2;
import com.mogo.module.common.MogoApisHandler;
import com.mogo.utils.UiThreadHandler;
import com.mogo.utils.logger.Logger;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

View File

@@ -16,9 +16,9 @@ import com.mogo.eagle.core.function.v2x.trafficlight.core.TrafficLightThreadHand
import com.mogo.eagle.core.function.v2x.trafficlight.core.TrafficLightThreadHandler.Companion.MSG_WHAT_STOP_SEARCH_CROSS_ROAD
import com.mogo.eagle.core.function.v2x.trafficlight.core.TrafficLightThreadHandler.Companion.MSG_WHAT_STOP_SEARCH_TRAFFIC_LIGHT
import com.mogo.eagle.core.function.v2x.trafficlight.network.TrafficLightNetWorkModel
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.map.navi.IMogoCarLocationChangedListener2
import com.mogo.module.common.MogoApisHandler
import com.mogo.utils.logger.Logger
class MogoTrafficLightManager : IMogoCarLocationChangedListener2 {

View File

@@ -15,11 +15,11 @@ import com.mogo.eagle.core.function.call.trafficlight.CallTrafficLightListenerMa
import com.mogo.eagle.core.function.call.vip.CallVipSetListenerManager
import com.mogo.eagle.core.function.v2x.trafficlight.core.MogoTrafficLightManager
import com.mogo.eagle.core.function.v2x.vip.network.VipNetWorkModel
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import com.mogo.eagle.core.utilcode.util.UiThreadHandler
import com.mogo.module.common.MogoApisHandler
import com.mogo.module.common.enums.EventTypeEnum
import com.mogo.service.cloud.socket.IMogoOnMessageListener
import com.mogo.utils.UiThreadHandler
import com.mogo.utils.logger.Logger
import kotlin.math.abs
class VipCarManager : IMogoOnMessageListener<VipMessage>, IMoGoTrafficLightListener,

View File

@@ -38,16 +38,31 @@ android {
targetCompatibility JavaVersion.VERSION_1_8
}
kapt.includeCompileClasspath = false
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation rootProject.ext.dependencies.androidxappcompat
kapt rootProject.ext.dependencies.androidxannotation
api rootProject.ext.dependencies.glide
kapt rootProject.ext.dependencies.glidecompiler
implementation rootProject.ext.dependencies.kotlinstdlibjdk7
implementation rootProject.ext.dependencies.androidxannotation
implementation rootProject.ext.dependencies.material
implementation rootProject.ext.dependencies.gson
implementation rootProject.ext.dependencies.glideanno
implementation rootProject.ext.dependencies.glideokhttp3
implementation rootProject.ext.dependencies.coroutinescore
implementation rootProject.ext.dependencies.coroutinesandroid
api rootProject.ext.dependencies.mogoaicloudpassport
api 'ch.hsr:geohash:1.4.0'
api rootProject.ext.dependencies.mogoaicloudnetwork
}
apply from: new File(rootProject.rootDir, "gradle/upload.gradle").toString()

View File

@@ -0,0 +1,36 @@
package com.mogo.eagle.core.utilcode.mogo.glide;
import android.content.Context;
import android.util.Log;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.engine.cache.ExternalPreferredCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.executor.GlideExecutor;
import com.bumptech.glide.module.AppGlideModule;
/**
* Created by congtaowang on 2018/12/17.
*/
@GlideModule
public class BaseGlideModule extends AppGlideModule {
public static final int MEMORY_CACHE_SIZE = 5 * 1024 * 1024;
public static final int DISK_CACHE_SIZE = 50 * 1024 * 1024;
public static final String DISK_CACHE_NAME = "glide";
@Override
public void applyOptions( Context context, GlideBuilder builder ) {
super.applyOptions( context, builder );
/**
* 更改缓存最总文件夹名称
*
* 是在sdcard/Android/data/包名/cache/DISK_CACHE_NAME目录当中
*/
builder.setLogLevel(Log.VERBOSE);
builder.setMemoryCache( new LruResourceCache( MEMORY_CACHE_SIZE ) );
builder.setDiskCache( new ExternalPreferredCacheDiskCacheFactory( context, DISK_CACHE_NAME, DISK_CACHE_SIZE ) );
builder.setDiskCacheExecutor(GlideExecutor.newDiskCacheExecutor(GlideExecutor.UncaughtThrowableStrategy.DEFAULT));
}
}

View File

@@ -0,0 +1,67 @@
package com.mogo.eagle.core.utilcode.mogo.glide;
import android.content.Context;
import android.graphics.Bitmap;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.mogo.eagle.core.utilcode.mogo.logger.Logger;
import androidx.annotation.NonNull;
/**
* 使用Glide加载图片时使该图片进行高斯模糊
* 基本用法Glide.with(this).load(userInfo.headImgurl).apply(RequestOptions.bitmapTransform(GlideBlurTransformation(this))).into(ivCardBg)
* 如果想用多个Transform可以使用{@link com.bumptech.glide.load.MultiTransformation} 进行Transform的融合
* @author tongchenfei
*/
public class GlideBlurTransformation extends CenterCrop {
private static final float DEFAULT_BLUR_RADIUS = 25F;
private static final float DEFAULT_OUT_WIDTH_SCALE = 0.5F;
private Context context;
private float blurRadius;
private float outScale;
public GlideBlurTransformation(Context context) {
this(context, DEFAULT_BLUR_RADIUS);
}
public GlideBlurTransformation(Context context, float blurRadius) {
this(context, blurRadius, DEFAULT_OUT_WIDTH_SCALE);
}
public GlideBlurTransformation(Context context, float blurRadius, float outWidthScale) {
this.context = context;
this.blurRadius = blurRadius;
this.outScale = outWidthScale;
}
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform,
int outWidth, int outHeight) {
Bitmap bitmap = super.transform(pool, toTransform, outWidth, outHeight);
Logger.d("GlideBlurTransformation", "transform=== blurRadius: " + blurRadius + " " +
"outScale: " + outScale);
return blurBitmap(bitmap, blurRadius, (int) (outWidth * outScale), (int) (outHeight * outScale));
}
private Bitmap blurBitmap(Bitmap bitmap, float blurRadius, int outWidth, int outHeight) {
Bitmap inputBitmap = Bitmap.createScaledBitmap(bitmap, outWidth, outHeight, false);
Bitmap outBitmap = Bitmap.createBitmap(inputBitmap);
RenderScript renderScript = RenderScript.create(context);
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(renderScript,
Element.U8_4(renderScript));
Allocation tmpIn = Allocation.createFromBitmap(renderScript, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(renderScript, outBitmap);
blurScript.setRadius(blurRadius);
blurScript.setInput(tmpIn);
blurScript.forEach(tmpOut);
tmpOut.copyTo(outBitmap);
return outBitmap;
}
}

View File

@@ -0,0 +1,167 @@
package com.mogo.eagle.core.utilcode.mogo.glide;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.mogo.eagle.core.utilcode.util.BuildConfig;
import java.security.MessageDigest;
import androidx.annotation.NonNull;
/**
* Glide加载图片使图片变成圆角图片工具
* 基本用法Glide.with(this).load(imgUrl).apply(RequestOptions.bitmapTransform(GlideRoundedCornersTransform(this))).into(imageView)
* 如果想用多个Transform可以使用{@link com.bumptech.glide.load.MultiTransformation} 进行Transform的融合
* @author tongchenfei
*/
public class GlideRoundedCornersTransform extends CenterCrop {
private float mRadius;
private 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);
/**
* 待处理的圆角枚举
*/
public enum CornerType {
ALL,
TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT,
TOP, BOTTOM, LEFT, RIGHT,
TOP_LEFT_BOTTOM_RIGHT,
TOP_RIGHT_BOTTOM_LEFT,
TOP_LEFT_TOP_RIGHT_BOTTOM_RIGHT,
TOP_RIGHT_BOTTOM_RIGHT_BOTTOM_LEFT,
TOP_LEFT_TOP_RIGHT
}
public GlideRoundedCornersTransform(float radius, CornerType cornerType) {
super();
mRadius = radius;
mCornerType = cornerType;
}
@Override
protected Bitmap transform(@NonNull BitmapPool pool,@NonNull Bitmap toTransform, int outWidth, int outHeight) {
Bitmap transform = super.transform(pool, toTransform, outWidth, outHeight);
return roundCrop(pool, transform);
}
private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
if (source == null) {
return null;
}
int width = source.getWidth();
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);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader
.TileMode.CLAMP));
paint.setAntiAlias(true);
Path path = new Path();
drawRoundRect(canvas, paint, path, width, height);
return result;
}
private void drawRoundRect(Canvas canvas, Paint paint, Path path, int width, int height) {
float[] rids;
switch (mCornerType) {
case ALL:
rids = new float[]{mRadius, mRadius, mRadius, mRadius, mRadius, mRadius, mRadius, mRadius};
drawPath(rids, canvas, paint, path, width, height);
break;
case TOP_LEFT:
rids = new float[]{mRadius, mRadius, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
drawPath(rids, canvas, paint, path, width, height);
break;
case TOP_RIGHT:
rids = new float[]{0.0f, 0.0f, mRadius, mRadius, 0.0f, 0.0f, 0.0f, 0.0f};
drawPath(rids, canvas, paint, path, width, height);
break;
case BOTTOM_RIGHT:
rids = new float[]{0.0f, 0.0f, 0.0f, 0.0f, mRadius, mRadius, 0.0f, 0.0f};
drawPath(rids, canvas, paint, path, width, height);
break;
case BOTTOM_LEFT:
rids = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, mRadius, mRadius};
drawPath(rids, canvas, paint, path, width, height);
break;
case TOP:
rids = new float[]{mRadius, mRadius, mRadius, mRadius, 0.0f, 0.0f, 0.0f, 0.0f};
drawPath(rids, canvas, paint, path, width, height);
break;
case BOTTOM:
rids = new float[]{0.0f, 0.0f, 0.0f, 0.0f, mRadius, mRadius, mRadius, mRadius};
drawPath(rids, canvas, paint, path, width, height);
break;
case LEFT:
rids = new float[]{mRadius, mRadius, 0.0f, 0.0f, 0.0f, 0.0f, mRadius, mRadius};
drawPath(rids, canvas, paint, path, width, height);
break;
case RIGHT:
rids = new float[]{0.0f, 0.0f, mRadius, mRadius, mRadius, mRadius, 0.0f, 0.0f};
drawPath(rids, canvas, paint, path, width, height);
break;
case TOP_LEFT_BOTTOM_RIGHT:
rids = new float[]{mRadius, mRadius, 0.0f, 0.0f, mRadius, mRadius, 0.0f, 0.0f};
drawPath(rids, canvas, paint, path, width, height);
break;
case TOP_RIGHT_BOTTOM_LEFT:
rids = new float[]{0.0f, 0.0f, mRadius, mRadius, 0.0f, 0.0f, mRadius, mRadius};
drawPath(rids, canvas, paint, path, width, height);
break;
case TOP_LEFT_TOP_RIGHT_BOTTOM_RIGHT:
rids = new float[]{mRadius, mRadius, mRadius, mRadius, mRadius, mRadius, 0.0f, 0.0f};
drawPath(rids, canvas, paint, path, width, height);
break;
case TOP_RIGHT_BOTTOM_RIGHT_BOTTOM_LEFT:
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");
}
}
/**
* @param rids 圆角的半径依次为左上角xy半径右上角右下角左下角
*/
private void drawPath(float[] rids, Canvas canvas, Paint paint, Path path, int width, int height) {
path.addRoundRect(new RectF(0, 0, width, height), rids, Path.Direction.CW);
canvas.drawPath(path, paint);
}
@Override
public boolean equals(Object o) {
return o instanceof GlideRoundedCornersTransform;
}
@Override
public int hashCode() {
return ID.hashCode();
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {
messageDigest.update(ID_BYTES);
}
}

View File

@@ -0,0 +1,58 @@
package com.mogo.eagle.core.utilcode.mogo.permissions;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
/**
* @author xiaoyuzhou
* @date 2021/7/22 4:57 下午
*/
public class PermissionsDialogUtils {
public static AlertDialog mAlertDialog;
/**
* 打开APP的详情设置
*/
public static void openAppDetails(Activity activity, String msg, int CODE_WINDOW) {
if (mAlertDialog == null || !mAlertDialog.isShowing()) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
if (TextUtils.isEmpty(msg)) {
builder.setMessage("请在 “应用信息 -> 权限” 中授予权限");
} else {
builder.setMessage("请在 “应用信息 -> 权限” 中授予【" + msg + "】权限");
}
builder.setPositiveButton("手动授权", (dialog, which) -> {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + activity.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
activity.startActivityForResult(intent, CODE_WINDOW);
});
builder.setCancelable(false);
mAlertDialog = builder.show();
}
}
/**
* 跳转浮层权限获取页面
*
* @param activity
* @param CODE_WINDOW
*/
public static void openOverlayPermission(Activity activity, int CODE_WINDOW) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + activity.getPackageName())), CODE_WINDOW);
}
}
}

View File

@@ -0,0 +1,488 @@
package com.mogo.eagle.core.utilcode.mogo.sqlite;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.mogo.eagle.core.utilcode.mogo.logger.Logger;
import com.mogo.utils.sqlite.annotation.DbField;
import com.mogo.utils.sqlite.annotation.DbTable;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 数据库操作
*
* @param <T>
* @author donghongyu
*/
public class SQLBaseDao<T> implements SQLIDao<T> {
private String TAG = "SQLBaseDao";
//数据库操作的引用
private SQLiteDatabase sqLiteDatabase;
//要操作的数据实体的引用
private Class<T> entityClass;
//要操作的数据表名称
private String tableName;
//记录数据表是否存在
private boolean isInit = false;
//因为反射会消耗时间,这里使用缓存,进行性能优化
//缓存空间key-字段名,标注的自定义注解 value-成员变量)
private HashMap<String, Field> cacheField;
@Override
public boolean init(@NotNull SQLiteDatabase sqLiteDatabase, @NotNull Class<T> entityClass) {
this.sqLiteDatabase = sqLiteDatabase;
this.entityClass = entityClass;
//自动建表(只创建一次)
if (!isInit) {
//获取表名
tableName = entityClass.getAnnotation(DbTable.class).tableName();
//如果数据库没有建立连接跳出操作防止异常信息
if (!sqLiteDatabase.isOpen()) {
return false;
}
//执行Sql进行自动建表
String createTableSql = getCreateTableSql();
Logger.d(TAG, "执行SQL" + createTableSql);
sqLiteDatabase.execSQL(createTableSql);
//初始化缓存空间
cacheField = new HashMap();
initCacheField();
//标记已经创建过数据表
isInit = true;
}
return isInit;
}
/**
* 插入数据
*
* @param entity 要插入数据的数据对象爱你那个
* @return 插入结果ID如果发生错误则为-1
*/
@Override
public long insert(T entity) {
//1、准备好ContentValues中的数据
//2、设置插入的内容
ContentValues values = getContentValuesForInsert(entity);
//3、执行插入
long result;
if (sqLiteDatabase != null && sqLiteDatabase.isOpen()) {
result = sqLiteDatabase.insert(tableName, null, values);
} else {
result = -1;
}
return result;
}
/**
* 删除数据
*
* @param where 要删除的对象,对象的字段如果赋值,则代表查询条件
* @return 受影响行数
*/
@Override
public int delete(T where) {
// 拼接查询条件
Condition condition = new Condition(getContentValuesForQuery(where));
int result;
if (sqLiteDatabase != null && sqLiteDatabase.isOpen()) {
//受影响行数
result = sqLiteDatabase.delete(
tableName,
condition.getWhereCause(),
condition.getWhereArgs()
);
} else {
result = -1;
}
return result;
}
/**
* 更新数据
*
* @param where 要更新的对象,对象的字段如果赋值,则代表查询条件
* @param newEntity 新的数据内容
* @return 受影响行数
*/
@Override
public int update(T where, T newEntity) {
Condition condition = new Condition(getContentValuesForQuery(where));
int result;
if (sqLiteDatabase != null && sqLiteDatabase.isOpen()) {
//受影响行数
result = sqLiteDatabase.update(
tableName,
getContentValuesForInsert(newEntity),
condition.getWhereCause(),
condition.getWhereArgs()
);
} else {
result = -1;
}
return result;
}
/**
* 查询数据
*
* @param where 查询条件对象,同时也用来初始化对象使用
*/
@NotNull
@Override
public List<T> query(T where) {
return query(where, null, null, null);
}
/**
* 查询数据
*
* @param where 查询条件对象,同时也用来初始化对象使用
*/
@NotNull
@Override
public List<T> query(T where, String orderBy) {
return query(where, orderBy, null, null);
}
/**
* @param where 根据条件 [where] 进行数据查询,如果[where]==只初始化不赋值 则代表查询所有数据
* @param orderBy 排序字段
* @param isOrderDESC 是否倒序 true-倒序false-正序
* @return 结果集合
*/
@Override
public List<T> query(T where, String orderBy, boolean isOrderDESC) {
if (isOrderDESC) {
orderBy = orderBy + " DESC";
}
return query(where, orderBy, null, null);
}
/**
* 查询数据
*
* @param where 查询条件对象
* @param orderBy 排序规则
* @param startIndex 开始的位置
* @param limit 限制查询得到的数据个数
*/
public ArrayList<T> query(T where, String orderBy, Integer startIndex, Integer limit) {
//拼接分页语句
String limitString = null;
if (startIndex != null && limit != null) {
limitString = startIndex + "," + limit;
}
Condition condition = new Condition(getContentValuesForQuery(where));
Cursor cursor = null;
//定义查询结果
ArrayList<T> result = new ArrayList<>();
if (sqLiteDatabase != null && sqLiteDatabase.isOpen()) {
try {
//查询数据库
cursor = sqLiteDatabase.query(
tableName,
null,
condition.getWhereCause(),
condition.getWhereArgs(),
null,
null,
orderBy,
limitString
);
//将查到结果添加到返回集合中
result.addAll(getQueryResult(cursor, where));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
return result;
}
/**
* 获取查询db结果
*/
private ArrayList<T> getQueryResult(Cursor cursor, T where) {
//定义查询结果
ArrayList<T> result = new ArrayList<>();
//Cursor从头读到尾
//游标从头读到尾
cursor.moveToFirst();
try {
if (where != null) {
//移动游标获取下一行数据
while (!cursor.isAfterLast()) {
//通过反射构建一个查询结果对象
T item = (T) where.getClass().newInstance();
Set<Map.Entry<String, Field>> fieldIterator = cacheField.entrySet();
for (Map.Entry<String, Field> stringFieldEntry : fieldIterator) {
//获取数据库字段名称
String columnName = stringFieldEntry.getKey();
//数据库字段名对应的数据对象的成员变量
Field field = stringFieldEntry.getValue();
//获取指定列名对应的索引
int columnIndex = cursor.getColumnIndex(columnName);
//获取成员变量数据类型
Class fieldType = field.getType();
if (columnIndex != -1) {
if (fieldType == (String.class)) {
field.set(item, cursor.getString(columnIndex));
} else if (fieldType == (Integer.class)) {
field.set(item, cursor.getInt(columnIndex));
} else if (fieldType == (Long.class)) {
field.set(item, cursor.getLong(columnIndex));
} else if (fieldType == (Double.class)) {
field.set(item, cursor.getDouble(columnIndex));
} else if (fieldType == (Boolean.class)) {
int value = cursor.getInt(columnIndex);
if (value == 0) {
field.set(item, false);
} else {
field.set(item, true);
}
} else if (fieldType == (byte[].class)) {
field.set(item, cursor.getBlob(columnIndex));
} else {
//未知类型
throw new UnsupportedOperationException("未定义的数据类型fieldName= " + columnName + " fieldType= " + fieldType);
}
}
}
//添加到结果集
result.add(item);
//移动到下一个位置
cursor.moveToNext();
}
}
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
cursor.close();
return result;
}
/**
* 初始化字段缓存
*/
private void initCacheField() {
//1.取到所有的列名(查询一个空表获取表结构,不影响性能)
if (sqLiteDatabase != null && sqLiteDatabase.isOpen()) {
String sqlQuery = "select * from " + tableName + " limit 1,0";
Cursor cursor = sqLiteDatabase.rawQuery(sqlQuery, null);
//获取所有的列名
String[] columnNames = cursor.getColumnNames();
//关闭资源
cursor.close();
//2.取所有成员名
Field[] columnFields = entityClass.getDeclaredFields();
//3.通过两层循环,进行对应关系建立
for (String columnName : columnNames) {
for (Field columnField : columnFields) {
if (columnName.equals(columnField.getAnnotation(DbField.class).fieldName())) {
columnField.setAccessible(true);
cacheField.put(columnName, columnField);
}
}
}
}
}
/**
* 拼装创建数据表的SQL语句
*/
private String getCreateTableSql() {
//create table if not exists tb_name(_id integer,name varchar2(20))
StringBuffer sqlCreateTable = new StringBuffer();
sqlCreateTable.append("create table if not exists ");
sqlCreateTable.append(tableName + " (");
//反射获取所有的数据对象内的成员变量
Field[] fields = entityClass.getDeclaredFields();
for (int index = 0; index < fields.length; index++) {
//字段名称
String columnName = fields[index].getAnnotation(DbField.class).fieldName();
//获取成员变量数据类型
Class fieldType = fields[index].getType();
if (fieldType == (String.class)) {
sqlCreateTable.append(columnName).append(" TEXT,");
} else if (fieldType == (Integer.class)) {
sqlCreateTable.append(columnName).append(" INTEGER,");
} else if (fieldType == (Long.class)) {
sqlCreateTable.append(columnName).append(" BIGINT,");
} else if (fieldType == (Double.class)) {
sqlCreateTable.append(columnName).append(" DOUBLE,");
} else if (fieldType == (Boolean.class)) {
sqlCreateTable.append(columnName).append(" INTEGER,");
} else if (fieldType == (byte[].class)) {
sqlCreateTable.append(columnName).append(" BLOB,");
} else {
//未知类型
throw new UnsupportedOperationException("未定义的数据类型fieldName= " + columnName + " fieldType= " + fieldType);
}
if (index == fields.length - 1) {
if (sqlCreateTable.toString().endsWith(",")) {
sqlCreateTable.deleteCharAt(sqlCreateTable.length() - 1);
}
}
}
sqlCreateTable.append(")");
return sqlCreateTable.toString();
}
/**
* 获取插入使用的ContentValues
*/
private ContentValues getContentValuesForInsert(T entity) {
ContentValues contentValues = new ContentValues();
Set<Map.Entry<String, Field>> fieldIterator = cacheField.entrySet();
for (Map.Entry<String, Field> stringFieldEntry : fieldIterator) {
try {
//获取变量的值
Object valueObject = stringFieldEntry.getValue().get(entity);
//获取列名
String columnName = stringFieldEntry.getKey();
//获取成员变量数据类型
Class fieldType = stringFieldEntry.getValue().getType();
if (fieldType == (String.class)) {
contentValues.put(columnName, (String) valueObject);
} else if (fieldType == (Integer.class)) {
contentValues.put(columnName, (Integer) valueObject);
} else if (fieldType == (Long.class)) {
contentValues.put(columnName, (Long) valueObject);
} else if (fieldType == (Double.class)) {
contentValues.put(columnName, (Double) valueObject);
} else if (fieldType == (Boolean.class)) {
if (((boolean) valueObject)) {
contentValues.put(columnName, 1);
} else {
contentValues.put(columnName, 0);
}
} else if (fieldType == (byte[].class)) {
contentValues.put(columnName, (byte[]) valueObject);
} else {
//未知类型
throw new UnsupportedOperationException("未定义的数据类型fieldName= " + columnName + " fieldType= " + fieldType);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Logger.d(TAG, "contentValues:" + contentValues);
return contentValues;
}
/**
* 获取查询使用的 条件值对象
*/
private ContentValues getContentValuesForQuery(T entity) {
ContentValues contentValues = new ContentValues();
try {
if (entity != null) {
Set<Map.Entry<String, Field>> fieldIterator = cacheField.entrySet();
for (Map.Entry<String, Field> stringFieldEntry : fieldIterator) {
if (stringFieldEntry.getValue().get(entity) != null) {
// 针对Boolean类型进行处理
if (stringFieldEntry.getValue().get(entity) instanceof Boolean) {
if ((boolean) stringFieldEntry.getValue().get(entity)) {
contentValues.put(stringFieldEntry.getKey(), "1");
} else {
contentValues.put(stringFieldEntry.getKey(), "0");
}
}
// 其它数据类型处理
else {
contentValues.put(stringFieldEntry.getKey(),
stringFieldEntry.getValue().get(entity).toString());
}
}
}
}
} catch (IllegalAccessError | IllegalAccessException e) {
e.printStackTrace();
}
return contentValues;
}
/**
* 条件拼接对象
*/
static class Condition {
/**
* 条件key拼接
* _id=?&&name=?
*/
private String whereCause;
/**
* 条件值,与 whereCause 顺序一致
*/
private String[] whereArgs;
//根据传入的contentValues转换成查询条件
public Condition(ContentValues whereContent) {
//记录后面填充到查询语句“?”上的数据参数
ArrayList<String> argList = new ArrayList<>();
//拼接查询语句
StringBuilder whereCaseSb = new StringBuilder();
/*
* 是为了链接下面的查询条件条件,也或者是替换没有查询条件的语句。
* 比如要把检索条件作为一个参数传递给SQL
* 那么当这个检索语句不存在的话就可以给它赋值为1=1.
* 这样就避免了SQL出错也就可以把加条件的SQL和不加条件的SQL合二为一。
*/
whereCaseSb.append(" 1=1 ");
Set<String> keys = whereContent.keySet();
//因为使用了“1=1”所以即便是这里没有任何数据拼接也是可以正常
for (String key : keys) {
Object valueObject = whereContent.get(key);
if (valueObject != null) {
String value = (String) valueObject;
//拼接查询条件语句
//1:1 and _id=? and name=?
whereCaseSb.append(" and " + key + " =?");
//记录对应的value
argList.add(value);
}
}
//集合转成数组
this.whereArgs = argList.toArray(new String[argList.size()]);
this.whereCause = whereCaseSb.toString();
}
public String getWhereCause() {
return this.whereCause;
}
public String[] getWhereArgs() {
return this.whereArgs;
}
}
}

View File

@@ -0,0 +1,78 @@
package com.mogo.utils.sqlite
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import com.mogo.eagle.core.utilcode.mogo.sqlite.SQLBaseDao
import com.mogo.eagle.core.utilcode.mogo.sqlite.SQLIDao
import com.mogo.utils.sqlite.annotation.DbDatabase
import com.mogo.utils.sqlite.proxy.BaseDaoProxyLog
/**
* <p>数据库处理工厂</p>
* Created by donghongyu on 2019/9/6.
*/
open class SQLDaoFactory {
//默认数据库名称
private var dbName = "MoGoSQLite.db"
companion object {
//单利工厂
private var sqlDaoFactory: SQLDaoFactory? = null
//数据库存储路径
private lateinit var sqLiteDatabasePath: String
//数据库操作类
private var sqLiteDatabase: SQLiteDatabase? = null
fun getInstance(): SQLDaoFactory {
if (sqlDaoFactory == null) {
synchronized(SQLDaoFactory::class.java) {
if (sqlDaoFactory == null) {
sqlDaoFactory = SQLDaoFactory()
}
}
}
return sqlDaoFactory!!
}
}
//获取数据库操作对象
fun <T : Any> getBaseDao(context: Context, entityClass: Class<T>): SQLIDao<T>? {
var baseDao: SQLIDao<T>? = null
try {
//获取数据库名称,如果没有设置则使用默认名称
val dbDatabase = entityClass.getAnnotation(DbDatabase::class.java)
if (dbDatabase != null) {
dbName = dbDatabase.dbName
}
//openOrCreateDatabase 如果不存在则先创建再打开数据库,如果存在则直接打开。
sqLiteDatabasePath =
"${context.getDir("database", Context.MODE_APPEND).path}/$dbName"
sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqLiteDatabasePath, null)
// 这里为了演示,添加了日志工具的叠加使用,根据需要可以自己修改
// baseDao = BaseDaoProxyShow().bind(BaseDaoProxyLog().bind(BaseDao<T>())) as IBaseDao<T>
// baseDao = BaseDaoProxyLog().bind(SQLBaseDao<T>()) as IBaseDao<T>
// baseDao = BaseDao<T>()
baseDao = BaseDaoProxyLog().bind(SQLBaseDao<T>()) as SQLIDao<T>
baseDao.init(sqLiteDatabase!!, entityClass)
} catch (e: Exception) {
e.printStackTrace()
}
return baseDao
}
/**
* 关闭数据库
*/
fun closeDatabase() {
sqLiteDatabase?.close()
}
}

View File

@@ -0,0 +1,53 @@
package com.mogo.eagle.core.utilcode.mogo.sqlite;
import android.database.sqlite.SQLiteDatabase;
import java.util.List;
/**
* 数据库操作接口
*
* @author donghongyu
*/
public interface SQLIDao<T> {
/**
* 初始化数据库连接
*/
boolean init(SQLiteDatabase sqLiteDatabase, Class<T> entityClass);
/**
* 将 [entity] 进行数据插入
*/
long insert(T entity);
/**
* 根据条件 [where] 进行数据删除,如果[where]==只初始化不赋值 则代表删除所有数据
*/
int delete(T where);
/**
* 根据条件 [where] 进行数据更新,如果[where]==只初始化不赋值 则代表删除所有数据
*/
int update(T where, T newEntity);
/**
* @param where 根据条件 [where] 进行数据查询,如果[where]==只初始化不赋值 则代表查询所有数据
* @return 结果集合
*/
List<T> query(T where);
/**
* @param where 根据条件 [where] 进行数据查询,如果[where]==只初始化不赋值 则代表查询所有数据
* @param orderBy 排序字段
* @return 结果集合
*/
List<T> query(T where, String orderBy);
/**
* @param where 根据条件 [where] 进行数据查询,如果[where]==只初始化不赋值 则代表查询所有数据
* @param orderBy 排序字段
* @param isOrderDESC 是否倒序
* @return 结果集合
*/
List<T> query(T where, String orderBy, boolean isOrderDESC);
}

View File

@@ -0,0 +1,15 @@
package com.mogo.utils.sqlite.annotation
/**
* <p>添加在要操作的数据对象名上面,用来设置数据库名称</p>
*
* /**
* * @DbDatabase("AppSQLite.db")
* * class UserEntity {}
* */
* Created by donghongyu on 2019/9/6.
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
annotation class DbDatabase(val dbName: String)

View File

@@ -0,0 +1,21 @@
package com.mogo.utils.sqlite.annotation
/**
* <p>添加在要处理的数据对象的字段之上,用来设置数据表的字段名称</p>
* /**
* *@DbTable("tb_user")
* *class UserEntity {
* * @DbField("_id")
* * var id: Int = 0
* * @DbField("name")
* * var name: String? = null
* * @DbField("password")
* * var password: String? = null
* *}
* */
* Created by donghongyu on 2019/9/6.
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
annotation class DbField(val fieldName: String)

View File

@@ -0,0 +1,15 @@
package com.mogo.utils.sqlite.annotation
/**
* <p>添加在要操作的数据对象名上面,用来设置数据表名称</p>
*
* /**
* * @DbTable("tb_user")
* * class UserEntity {}
* */
* Created by donghongyu on 2019/9/6.
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
annotation class DbTable(val tableName: String)

View File

@@ -0,0 +1,49 @@
package com.mogo.utils.sqlite.proxy
import com.mogo.eagle.core.utilcode.mogo.logger.Logger
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
/**
* 使用java实现动态代理数据库操作类加入日志功能
* Created by donghongyu on 2019/9/6.
*/
class BaseDaoProxyLog : InvocationHandler {
private var target: Any? = null
/**
* 绑定委托对象并返回一个【代理占位】
*
* @param target 真实对象
* @return 代理对象【占位】
*/
fun bind(target: Any): Any {
this.target = target
//取得代理对象
return Proxy.newProxyInstance(
target.javaClass.classLoader,
target.javaClass.interfaces, this
)
}
/**
* 同过代理对象调用方法首先进入这个方法.
*
* @param proxy --代理对象
* @param method -- 方法,被调用方法.
* @param args -- 方法的参数
*/
@Throws(Throwable::class)
override fun invoke(proxy: Any, method: Method, args: Array<Any>): Any? {
//反射方法前调用
Logger.i("SQL数据库管理", "当前执行>>${method.name}>>")
//反射执行方法 相当于调用target.sayHelllo;
val result: Any? = method.invoke(target, *args)
//反射方法后调用.
Logger.i("SQL数据库管理", "执行结果>>$result")
return result
}
}

View File

@@ -0,0 +1,154 @@
package com.mogo.eagle.core.utilcode.mogo.storage;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Set;
import androidx.annotation.NonNull;
public class SharedPrefsMgr {
private static final String File_Name = "app_shared_pref";
private static SharedPrefsMgr sInstance;
private static SharedPreferences sSharedPrefs;
public synchronized static SharedPrefsMgr getInstance( @NonNull Context context ) {
if ( sInstance == null ) {
try {
sInstance = new SharedPrefsMgr( context.getApplicationContext() );
} catch ( Exception e ) {
sInstance = new SharedPrefsMgr();
}
}
return sInstance;
}
private SharedPrefsMgr() {
}
private SharedPrefsMgr( Context context ) {
try {
sSharedPrefs = context.getSharedPreferences( File_Name, Context.MODE_PRIVATE );
} catch ( Exception e ) {
e.printStackTrace();
}
}
public void putString( String key, String value ) {
try {
SharedPreferences.Editor editor = sSharedPrefs.edit();
editor.putString( key, value );
editor.apply();
} catch ( Exception e ) {
}
}
public String getString( String tag ) {
try {
return sSharedPrefs.getString( tag, "" );
} catch ( Exception e ) {
return "";
}
}
public String getString( String tag, String defVal ) {
try {
return sSharedPrefs.getString( tag, defVal );
} catch ( Exception e ) {
return "";
}
}
public boolean getBoolean( String key, boolean defaultValue ) {
try {
return sSharedPrefs.getBoolean( key, defaultValue );
} catch ( Exception e ) {
return defaultValue;
}
}
public long getLong( String key, long defaultValue ) {
try {
return sSharedPrefs.getLong( key, defaultValue );
} catch ( Exception e ) {
return defaultValue;
}
}
public float getFloat( String key, float defaultValue ) {
try {
return sSharedPrefs.getFloat( key, defaultValue );
} catch ( Exception e ) {
return defaultValue;
}
}
public int getInt( String key, int value ) {
try {
return sSharedPrefs.getInt( key, value );
} catch ( Exception e ) {
return value;
}
}
public void putBoolean( String key, boolean value ) {
try {
SharedPreferences.Editor editor = sSharedPrefs.edit();
editor.putBoolean( key, value );
editor.apply();
} catch ( Exception e ) {
}
}
public void putLong( String key, long value ) {
try {
SharedPreferences.Editor editor = sSharedPrefs.edit();
editor.putLong( key, value );
editor.apply();
} catch ( Exception e ) {
}
}
public void putInt( String key, int value ) {
try {
SharedPreferences.Editor editor = sSharedPrefs.edit();
editor.putInt( key, value );
editor.apply();
} catch ( Exception e ) {
}
}
public void putFloat( String key, float value ) {
try {
SharedPreferences.Editor editor = sSharedPrefs.edit();
editor.putFloat( key, value );
editor.apply();
} catch ( Exception e ) {
}
}
public void remove( String key ) {
try {
SharedPreferences.Editor editor = sSharedPrefs.edit();
editor.remove( key );
editor.apply();
} catch ( Exception e ) {
}
}
public void putStringSet( String key, Set< String > values ) {
try {
SharedPreferences.Editor editor = sSharedPrefs.edit();
editor.putStringSet( key, values );
editor.apply();
} catch ( Exception e ) {
}
}
public Set<String> getStringSet( String key ) {
return sSharedPrefs.getStringSet( key, null );
}
}

View File

@@ -0,0 +1,77 @@
/*
* 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.eagle.core.utilcode.mogo.storage.lrucache;
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;
/** Junk drawer of utility methods. */
final class CacheUtil {
static final Charset US_ASCII = Charset.forName("US-ASCII");
static final Charset UTF_8 = Charset.forName("UTF-8");
private CacheUtil() {
}
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 imageContent 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) {
}
}
}
}

View File

@@ -0,0 +1,374 @@
package com.mogo.eagle.core.utilcode.mogo.storage.lrucache;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
public class DiskCacheManager {
private static DiskLruCache mDiskLruCache = null;
private DiskLruCache.Editor mEditor = null;
private DiskLruCache.Snapshot mSnapshot = null;
public static final long CACHE_MAXSIZE = 10 * 1024 * 1024;
public DiskCacheManager( Context context, String uniqueName) {
try {
if (mDiskLruCache != null) {
mDiskLruCache.close();
mDiskLruCache = null;
}
File cacheFile = getCacheFile(context, uniqueName);
mDiskLruCache = DiskLruCache.open(cacheFile, 1, 1, CACHE_MAXSIZE);
} catch ( IOException e) {
e.printStackTrace();
}
}
/**
* 获取缓存的路径 两个路径在卸载程序时都会删除,因此不会在卸载后还保留乱七八糟的缓存
* 有SD卡时获取 /sdcard/Android/data/<application package>/cache
* 无SD卡时获取 /data/labelList/<application package>/cache
*
* @param context 上下文
* @param uniqueName 缓存目录下的细分目录,用于存放不同类型的缓存
* @return 缓存目录 File
*/
private File getCacheFile( Context context, String uniqueName) {
String cachePath = null;
try {
cachePath = context.getCacheDir().getPath();
}catch ( Exception e){
e.printStackTrace();
}
return new File(cachePath + File.separator + uniqueName);
}
/**
* 获取缓存 editor
*
* @param key 缓存的key
* @return editor
* @throws IOException
*/
private DiskLruCache.Editor edit( String key) throws IOException {
key = SecretUtil.getMD5Result(key); //存取的 key
if (mDiskLruCache != null) {
mEditor = mDiskLruCache.edit(key);
}
return mEditor;
}
/**
* 根据 key 获取缓存缩略
*
* @param key 缓存的key
* @return Snapshot
*/
private DiskLruCache.Snapshot snapshot( String key) {
if (mDiskLruCache != null) {
try {
mSnapshot = mDiskLruCache.get(key);
} catch ( IOException e) {
e.printStackTrace();
}
}
return mSnapshot;
}
/*************************
* 字符串读写
*************************/
/**
* 缓存 String
*
* @param key 缓存文件键值MD5加密结果作为缓存文件名
* @param value 缓存内容
*/
public void put( String key, String value) {
DiskLruCache.Editor editor = null;
BufferedWriter writer = null;
try {
editor = edit(key);
if (editor == null) {
return;
}
OutputStream os = editor.newOutputStream(0);
writer = new BufferedWriter(new OutputStreamWriter(os));
writer.write(value);
editor.commit();
} catch ( IOException e) {
e.printStackTrace();
try {
if (editor != null)
editor.abort();
} catch ( IOException e1) {
e1.printStackTrace();
}
} finally {
try {
if (writer != null) {
writer.close();
}
} catch ( IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取字符串缓存
*
* @param key cache'key
* @return string
*/
public String getString( String key) {
InputStream inputStream = getCacheInputStream(key);
if (inputStream == null) {
return null;
}
try {
return inputStream2String(inputStream);
} catch ( IOException e) {
e.printStackTrace();
return null;
} finally {
try {
inputStream.close();
} catch ( IOException e1) {
e1.printStackTrace();
}
}
}
/*************************
* Json对象读写
*************************/
//Json 数据转换成 String 存储
public void put( String key, JSONObject value) {
put(key, value.toString());
}
//取得 json 字符串再转为 Json对象
public JSONObject getJsonObject( String key) {
String json = getString(key);
try {
return new JSONObject(json);
} catch ( JSONException e) {
e.printStackTrace();
return null;
}
}
/*************************
* Json数组对象读写
*************************/
public void put( String key, JSONArray array) {
put(key, array.toString());
}
public JSONArray getJsonArray( String key) {
try {
return new JSONArray(getString(key));
} catch ( JSONException e) {
e.printStackTrace();
return null;
}
}
/*************************
* byte 数据读写
*************************/
/**
* 存入byte数组
*
* @param key cache'key
* @param bytes bytes to save
*/
public void put( String key, byte[] bytes) {
OutputStream out = null;
DiskLruCache.Editor editor = null;
try {
editor = edit(key);
if (editor == null) {
return;
}
out = editor.newOutputStream(0);
out.write(bytes);
out.flush();
editor.commit();
} catch ( IOException e) {
e.printStackTrace();
try {
if (editor != null) {
editor.abort();
}
} catch ( IOException e1) {
e1.printStackTrace();
}
} finally {
if (out != null) {
try {
out.close();
} catch ( IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取缓存的 byte 数组
*
* @param key cache'key
* @return bytes
*/
public byte[] getBytes( String key) {
byte[] bytes = null;
InputStream inputStream = getCacheInputStream(key);
if (inputStream == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[256];
int len = 0;
try {
while ((len = inputStream.read(buf)) != -1) {
bos.write(buf, 0, len);
}
bytes = bos.toByteArray();
} catch ( IOException e) {
e.printStackTrace();
}
return bytes;
}
/*************************
* 序列化对象数据读写
*************************/
/**
* 序列化对象写入
*
* @param key cache'key
* @param object 待缓存的序列化对象
*/
public void put( String key, Serializable object) {
ObjectOutputStream oos = null;
DiskLruCache.Editor editor = null;
try {
editor = edit(key);
if (editor == null) {
return;
}
oos = new ObjectOutputStream(editor.newOutputStream(0));
oos.writeObject(object);
oos.flush();
editor.commit();
} catch ( IOException e) {
e.printStackTrace();
try {
if (editor != null)
editor.abort();
} catch ( IOException e1) {
e1.printStackTrace();
}
} finally {
try {
if (oos != null) {
oos.close();
}
} catch ( IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取 序列化对象
*
* @param key cache'key
* @param <T> 对象类型
* @return 读取到的序列化对象
*/
@SuppressWarnings("unchecked")
public <T> T getSerializable( String key) {
T object = null;
ObjectInputStream ois = null;
InputStream in = getCacheInputStream(key);
if (in == null) {
return null;
}
try {
ois = new ObjectInputStream(in);
object = (T) ois.readObject();
} catch ( IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return object;
}
/************************************************************************
********************** 辅助工具方法 分割线 ****************************
************************************************************************/
/**
* inputStream 转 String
*
* @param is 输入流
* @return 结果字符串
*/
private String inputStream2String( InputStream is) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
}
/**
* 获取 缓存数据的 InputStream
*
* @param key cache'key
* @return InputStream
*/
private InputStream getCacheInputStream( String key) {
key = SecretUtil.getMD5Result(key);
InputStream in;
DiskLruCache.Snapshot snapshot = snapshot(key);
if (snapshot == null) {
return null;
}
in = snapshot.getInputStream(0);
return in;
}
/**
* 同步记录文件
*/
public static void flush() {
if (mDiskLruCache != null) {
try {
mDiskLruCache.flush();
} catch ( IOException e) {
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,947 @@
/*
* 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.eagle.core.utilcode.mogo.storage.lrucache;
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 <strong>[a-z0-9_-]{1,120}</strong>. Values are byte sequences,
* accessible as streams or files. Each value must be between {@code 0} and
* {@code Integer.MAX_VALUE} bytes in length.
*
* <p>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.
*
* <p>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.
*
* <p>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.
* <ul>
* <li>When an entry is being <strong>created</strong> it is necessary to
* supply a full set of values; the empty value should be used as a
* placeholder if necessary.
* <li>When an entry is being <strong>edited</strong>, it is not necessary
* to supply data for every value; values default to their previous
* value.
* </ul>
* 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.
*
* <p>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.
*
* <p>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.
*/
public 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 String STRING_KEY_PATTERN = "[a-z0-9_-]{1,120}";
static final Pattern LEGAL_KEY_PATTERN = Pattern.compile(STRING_KEY_PATTERN);
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 final int valueCount;
private long size = 0;
private Writer journalWriter;
private final LinkedHashMap< String, Entry> lruEntries =
new LinkedHashMap< String, Entry>(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< Runnable >());
private final Callable< Void > cleanupCallable = new Callable< Void >() {
public Void call() throws Exception {
synchronized (DiskLruCache.this) {
if (journalWriter == null) {
return null; // Closed.
}
trimToSize();
if (journalRebuildRequired()) {
rebuildJournal();
redundantOpCount = 0;
}
}
return null;
}
};
private DiskLruCache( File directory, int appVersion, int valueCount, long maxSize) {
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;
}
/**
* 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
* @throws IOException if reading or writing the cache directory fails
*/
public static DiskLruCache open( File directory, int appVersion, int valueCount, long maxSize)
throws IOException {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 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);
if (cache.journalFile.exists()) {
try {
cache.readJournal();
cache.processJournal();
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);
cache.rebuildJournal();
return cache;
}
private void readJournal() throws IOException {
StrictLineReader reader = new StrictLineReader(new FileInputStream(journalFile), CacheUtil.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();
// If we ended on a truncated line, rebuild the journal before appending to it.
if (reader.hasUnterminatedLine()) {
rebuildJournal();
} else {
journalWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(journalFile, true), CacheUtil.US_ASCII));
}
} finally {
CacheUtil.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<Entry> 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];
}
} 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), CacheUtil.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), CacheUtil.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.
InputStream[] ins = new InputStream[valueCount];
try {
for (int i = 0; i < valueCount; i++) {
ins[i] = new FileInputStream(entry.getCleanFile(i));
}
} catch ( FileNotFoundException e) {
// A file must have been deleted manually!
for (int i = 0; i < valueCount; i++) {
if (ins[i] != null) {
CacheUtil.closeQuietly(ins[i]);
} else {
break;
}
}
return null;
}
redundantOpCount++;
journalWriter.append(READ + ' ' + key + '\n');
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
return new Snapshot(key, entry.sequenceNumber, 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;
}
/**
* 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;
}
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;
}
} 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 || 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];
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();
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<Entry>(lruEntries.values())) {
if (entry.currentEditor != null) {
entry.currentEditor.abort();
}
}
trimToSize();
journalWriter.close();
journalWriter = null;
}
private void trimToSize() throws IOException {
while (size > maxSize) {
Map.Entry< String, 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();
CacheUtil.deleteContents(directory);
}
private void validateKey( String key) {
Matcher matcher = LEGAL_KEY_PATTERN.matcher(key);
if (!matcher.matches()) {
throw new IllegalArgumentException("keys must match regex "
+ STRING_KEY_PATTERN + ": \"" + key + "\"");
}
}
private static String inputStreamToString( InputStream in) throws IOException {
return CacheUtil.readFully(new InputStreamReader(in, CacheUtil.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 final InputStream[] ins;
private final long[] lengths;
private Snapshot( String key, long sequenceNumber, InputStream[] ins, long[] lengths) {
this.key = key;
this.sequenceNumber = sequenceNumber;
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 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) {
CacheUtil.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 {
if (index < 0 || index >= valueCount) {
throw new IllegalArgumentException("Expected index " + index + " to "
+ "be greater than 0 and less than the maximum value count "
+ "of " + valueCount);
}
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), CacheUtil.UTF_8);
writer.write(value);
} finally {
CacheUtil.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");
}
}
}

View File

@@ -0,0 +1,34 @@
package com.mogo.eagle.core.utilcode.mogo.storage.lrucache;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SecretUtil {
public static String getMD5Result( String value) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(value.getBytes("UTF-8"));
byte[] result = md.digest();
return getString(result);
} catch ( NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
} catch ( UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
private static String getString( byte[] result) {
StringBuilder sb = new StringBuilder();
for (byte b : result) {
int i = b & 0xff;
if (i <= 0xf) {
sb.append(0);
}
sb.append( Integer.toHexString(i));
}
return sb.toString().toLowerCase();
}
}

View File

@@ -0,0 +1,196 @@
/*
* 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.eagle.core.utilcode.mogo.storage.lrucache;
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.
*
* <p>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}.
*
* <p>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.
*
* <p>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(CacheUtil.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 labelList.
// 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();
}
}
}
}
}
public boolean hasUnterminatedLine() {
return end == -1;
}
/**
* 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;
}
}

View File

@@ -0,0 +1,354 @@
package com.mogo.eagle.core.utilcode.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.HashMap;
public class ActivityLifecycleManager {
private Application mApplication;
/**
* 当前出于 Start 状态的 Activity
*/
private ArrayList<Activity> mStartedActivities = new ArrayList<>();
private ArrayList<AppStateListener> mAppStateListeners = new ArrayList<>();
/**
* 当前存活的 Activity
*/
private HashMap<Activity, ActivityTrace> mAliveActivities = new HashMap<>();
/**
* App 是否出于前台
*/
private volatile boolean mIsAppActive = false;
private Activity mCurrentResumedActivity;
/**
* Home 键事件广播的接受器
*/
private HomeKeyEventReceiver mHomeKeyEventReceiver;
/**
* Home 键事件监听者列表
*/
private ArrayList<HomeKeyEventListener> mHomeKeyEventListeners = new ArrayList<>();
private DefActivityLifecycleCallbacks mInnerActivityListener = new DefActivityLifecycleCallbacks() {
@Override
public void onActivityStarted(Activity activity) {
if (mStartedActivities.isEmpty()) {
mIsAppActive = true;
notifyAppStateChanged(AppStateListener.ACTIVE);
}
mStartedActivities.add(activity);
ActivityTrace trace = mAliveActivities.get(activity);
if (trace != null) {
trace.startCnt++;
}
}
@Override
public void onActivityStopped(Activity activity) {
mStartedActivities.remove(activity);
if (mStartedActivities.isEmpty()) {
mIsAppActive = false;
notifyAppStateChanged(AppStateListener.INACTIVE);
}
ActivityTrace trace = mAliveActivities.get(activity);
if (trace != null) {
trace.stopCnt++;
}
}
@Override
public void onActivityResumed(Activity activity) {
mCurrentResumedActivity = activity;
ActivityTrace trace = mAliveActivities.get(activity);
if (trace != null) {
trace.resumeCnt++;
}
}
@Override
public void onActivityPaused(Activity activity) {
ActivityTrace trace = mAliveActivities.get(activity);
if (trace != null) {
trace.pauseCnt++;
}
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
mAliveActivities.put(activity, new ActivityTrace(activity));
}
@Override
public void onActivityDestroyed(Activity activity) {
mAliveActivities.remove(activity);
}
};
private ActivityLifecycleManager() {
}
public static ActivityLifecycleManager getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private static final ActivityLifecycleManager INSTANCE = new ActivityLifecycleManager();
}
public void start(Application application) {
this.mApplication = application;
registerInnerActivityListener();
registerHomeKeyEventReceiver();
}
public void stop() {
unregisterActivityLifecycleCallbacks(mInnerActivityListener);
unregisterHomeKeyEventReceiver();
}
/**
* 注册 Activity 生命周期的回调
*
* @param callbacks Activity 生命周期的回调
*/
public void registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callbacks) {
if (mApplication == null) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return;
}
mApplication.registerActivityLifecycleCallbacks(callbacks);
}
/**
* 取消注册 Activity 生命周期的回调
*
* @param callbacks Activity 生命周期的回调
*/
public void unregisterActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callbacks) {
if (mApplication == null) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return;
}
mApplication.unregisterActivityLifecycleCallbacks(callbacks);
}
/**
* 应用是否出于前台
*/
public boolean isAppActive() {
return mIsAppActive;
}
public void setAppActive(boolean appActive) {
mIsAppActive = appActive;
}
public Activity getCurrentActivity() {
return mCurrentResumedActivity;
}
/**
* 添加应用状态的监听
*/
public void addAppStateListener(AppStateListener listener) {
synchronized (mAppStateListeners) {
mAppStateListeners.add(listener);
}
}
/**
* 移除应用状态的监听
*
* @param listener
*/
public void removeAppStateListener(AppStateListener listener) {
synchronized (mAppStateListeners) {
mAppStateListeners.remove(listener);
}
}
/**
* 添加 home 键的事件监听
*/
public void addHomeKeyEventListener(HomeKeyEventListener listener) {
if (listener == null) {
return;
}
synchronized (mHomeKeyEventListeners) {
mHomeKeyEventListeners.add(listener);
}
}
/**
* 移除 home 键的事件监听
*/
public void removeHomeKeyEventListener(HomeKeyEventListener listener) {
if (listener == null) {
return;
}
synchronized (mHomeKeyEventListeners) {
mHomeKeyEventListeners.remove(listener);
}
}
/**
* 注册Activity生命周期的监听
*/
private void registerInnerActivityListener() {
registerActivityLifecycleCallbacks(mInnerActivityListener);
}
private void notifyAppStateChanged(int state) {
Object[] listeners = collectAppStateListeners();
if (listeners != null) {
for (int i = 0; i < listeners.length; i++) {
((AppStateListener) listeners[i]).onStateChanged(state);
}
}
}
private Object[] collectAppStateListeners() {
Object[] listeners = null;
synchronized (mAppStateListeners) {
if (mAppStateListeners.size() > 0) {
listeners = mAppStateListeners.toArray();
}
}
return listeners;
}
private Object[] collectHomeKeyEventListeners() {
Object[] listeners = null;
synchronized (mHomeKeyEventListeners) {
if (mHomeKeyEventListeners.size() > 0) {
listeners = mHomeKeyEventListeners.toArray();
}
}
return listeners;
}
private void registerHomeKeyEventReceiver() {
android.content.IntentFilter filter = new android.content.IntentFilter();
filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
mHomeKeyEventReceiver = new HomeKeyEventReceiver();
mApplication.registerReceiver(mHomeKeyEventReceiver, filter);
}
private void unregisterHomeKeyEventReceiver() {
mApplication.unregisterReceiver(mHomeKeyEventReceiver);
}
private void onHomeKeyPressed() {
Object[] listeners = collectHomeKeyEventListeners();
if (listeners != null) {
for (int i = 0; i < listeners.length; i++) {
((HomeKeyEventListener) listeners[i]).onHomeKeyPressed();
}
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static abstract class DefActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
public interface AppStateListener {
int INACTIVE = 0;
int ACTIVE = 1;
/**
* App 状态的回调
*/
void onStateChanged(int state);
}
/**
* home 键的监听
*/
public interface HomeKeyEventListener {
void onHomeKeyPressed();
}
/**
* Activity 的生命周期调用痕迹
*/
static class ActivityTrace {
Activity activity;
int resumeCnt;
int pauseCnt;
int startCnt;
int stopCnt;
ActivityTrace(Activity activity) {
this.activity = activity;
}
}
private final class HomeKeyEventReceiver extends BroadcastReceiver {
private final String SYSTEM_DIALOG_REASON_KEY = "reason";
private final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
onHomeKeyPressed();
}
}
}
}
}

View File

@@ -2,6 +2,7 @@ package com.mogo.eagle.core.utilcode.util;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
@@ -12,6 +13,8 @@ import android.content.pm.SigningInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
@@ -31,10 +34,106 @@ import androidx.annotation.Nullable;
*/
public final class AppUtils {
private static final String MOGO_MAP_SDK_VERSION = "MAP_SDK_VERSION";
private AppUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
public static String getCustomMapSDKVersion(Context context){
return getApplicationMetaValue(context,MOGO_MAP_SDK_VERSION);
}
private static String getApplicationMetaValue(Context context,String metaName){
try {
ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),PackageManager.GET_META_DATA);
Bundle bundle = applicationInfo.metaData;
if (bundle != null){
return bundle.getString(metaName);
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return "";
}
public static String getApplicationLabel( Context context, String pkgName ) {
try {
PackageManager pm = context.getPackageManager();
ApplicationInfo appInfo = pm.getApplicationInfo( pkgName, PackageManager.GET_META_DATA );
return pm.getApplicationLabel( appInfo ).toString();
} catch ( Exception e ) {
return null;
}
}
public static boolean isAppForeground( Context context ) {
if ( context != null ) {
ActivityManager activityManager = ( ActivityManager ) context.getSystemService( Context.ACTIVITY_SERVICE );
List< ActivityManager.RunningAppProcessInfo > processes = activityManager.getRunningAppProcesses();
for ( ActivityManager.RunningAppProcessInfo processInfo : processes ) {
if ( processInfo.processName.equals( context.getPackageName() ) ) {
if ( processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND ) {
return true;
}
}
}
}
return false;
}
public static boolean isAppForeground( Context context, String pkg ) {
if ( context != null ) {
ActivityManager activityManager = ( ActivityManager ) context.getSystemService( Context.ACTIVITY_SERVICE );
List< ActivityManager.RunningAppProcessInfo > processes = activityManager.getRunningAppProcesses();
for ( ActivityManager.RunningAppProcessInfo processInfo : processes ) {
if ( processInfo.processName.equals( pkg ) ) {
if ( processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND ) {
return true;
}
}
}
}
return false;
}
//获取已安装应用的 uid-1 表示未安装此应用或程序异常
public static int getPackageUid( Context context, String packageName ) {
try {
ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo( packageName, 0 );
if ( applicationInfo != null ) {
return applicationInfo.uid;
}
} catch ( Exception e ) {
return -1;
}
return -1;
}
/**
* 判断某一 uid 的程序是否有正在运行的进程,即是否存活
* Created by cafeting on 2017/2/4.
*
* @param context 上下文
* @param uid 已安装应用的 uid
* @return true 表示正在运行false 表示没有运行
*/
public static boolean isProcessRunning( Context context, int uid ) {
if ( context == null ) {
return false;
}
ActivityManager am = ( ActivityManager ) context.getSystemService( Context.ACTIVITY_SERVICE );
List< ActivityManager.RunningServiceInfo > runningServiceInfos = am.getRunningServices( 200 );
if ( runningServiceInfos.size() > 0 ) {
for ( ActivityManager.RunningServiceInfo appProcess : runningServiceInfos ) {
if ( uid == appProcess.uid ) {
return true;
}
}
}
return false;
}
/**
* Register the status of application changed listener.
*
@@ -680,6 +779,38 @@ public final class AppUtils {
return result;
}
public static boolean isApplicationBroughtToBackground( final Context context ) {
ActivityManager am = ( ActivityManager ) context.getSystemService( Context.ACTIVITY_SERVICE );
List< ActivityManager.RunningTaskInfo > tasks = am.getRunningTasks( 1 );
if ( !tasks.isEmpty() ) {
ComponentName topActivity = tasks.get( 0 ).topActivity;
if ( !topActivity.getPackageName().equals( context.getPackageName() ) ) {
return true;
}
}
return false;
}
public static boolean isAppInstalled( Context context, String pkg ) {
PackageInfo packageInfo;
if ( TextUtils.isEmpty( pkg ) ) {
return false;
}
try {
packageInfo = context.getPackageManager().getPackageInfo( pkg, 0 );
} catch ( PackageManager.NameNotFoundException e ) {
packageInfo = null;
e.printStackTrace();
}
if ( packageInfo == null ) {
return false;
} else {
return true;
}
}
/**
* Return the application's information.
* <ul>

View File

@@ -0,0 +1,38 @@
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
* <p>
* 读取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;
}
}

View File

@@ -0,0 +1,681 @@
package com.mogo.eagle.core.utilcode.util;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.opengl.GLES10;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import com.elegant.utils.IOUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
/**
* @author wangzhiyuan
* @since 2017/8/30
*/
public class BitmapHelper {
private static final String TAG = "BitmapHelper";
static int ONE_KB = 1024;
static int ONE_MB = ONE_KB * 1024;
static int SIZE_DEFAULT = 2048;
static int SIZE_LIMIT = 2048;
/**
* 根据原图添加圆角
*
* @param source
* @return
*/
public static Bitmap createRoundCornerImage( Bitmap source, float corner ) {
final Paint paint = new Paint();
paint.setAntiAlias( true );
Bitmap target = Bitmap.createBitmap( source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888 );
Canvas canvas = new Canvas( target );
RectF rect = new RectF( 0, 0, source.getWidth(), source.getHeight() );
canvas.drawRoundRect( rect, corner, corner, paint );
paint.setXfermode( new PorterDuffXfermode( PorterDuff.Mode.SRC_IN ) );
canvas.drawBitmap( source, 0, 0, paint );
return target;
}
public static byte[] bitmapToBytes( Bitmap bitmap ) {
if ( bitmap == null ) {
return null;
}
ByteArrayOutputStream bos = null;
byte[] result = null;
try {
bos = new ByteArrayOutputStream();
bitmap.compress( Bitmap.CompressFormat.JPEG, 100, bos );
result = bos.toByteArray();
} catch ( Exception e ) {
e.printStackTrace();
result = null;
} finally {
IOUtils.closeSilently( bos );
}
return result;
}
/**
* Use quality compression to compress bitmap's size to be smaller than a max size, and convert it to bytes thereafter.
* Note that this method will not report compressing ratio related data.
*
* @param bitmap data source
* @param maxSize unit in kb
* @return bytes after compressing bitmap to a size smaller than a specific max size.
*/
public static byte[] bitmapToBytes( Bitmap bitmap, int maxSize ) {
final long start = System.currentTimeMillis();
if ( bitmap == null ) {
return null;
}
final int maxSizeOfBytes = maxSize * ONE_KB;
ByteArrayOutputStream bos = null;
byte[] result = null;
try {
bos = new ByteArrayOutputStream();
int quality = 100;
int fullSize = 0;
do {
bos.reset();
bitmap.compress( Bitmap.CompressFormat.JPEG, quality, bos );
if ( quality == 100 ) {
fullSize = bos.size();
}
Log.i( TAG, "quality<---->size, " + quality + "<---->" + bos.size() / 1024 );
}
while ( bos.size() > maxSizeOfBytes && ( quality -= ( fullSize > ONE_MB ) ? 10 : 5 ) >= 0 );
result = bos.toByteArray();
final long end = System.currentTimeMillis();
Log.i( TAG,
"bitmap to bytes costs " + ( end - start ) + "ms, \n" +
"bitmap full size is " + ( fullSize / 1024 ) + "kb, \n" +
"bitmap final size is " + ( bos.size() / 1024 ) + "kb, \n" +
"bitmap quality is " + quality );
} catch ( Exception e ) {
e.printStackTrace();
result = null;
} finally {
IOUtils.closeSilently( bos );
}
return result;
}
/**
* Use quality compression to compress bitmap to be smaller than a specific max size.
*
* @param bitmap data source
* @param maxSize a specific max size which's unit is kb.
* @return a compressed bitmap smaller than the max size.
*/
public static Bitmap compressBitmap( Bitmap bitmap, int maxSize, final OnCompressListener listener ) {
if ( bitmap == null || bitmap.isRecycled() ) {
return null;
}
listener.onBeforeCompress();
ByteArrayOutputStream bos = null;
Bitmap target = null;
try {
bos = new ByteArrayOutputStream();
int quality = 100;
do {
bos.reset();
bitmap.compress( Bitmap.CompressFormat.JPEG, quality, bos );
}
while ( bos.size() / 1024 > maxSize && ( quality -= 5 ) >= 0 );
byte[] result = bos.toByteArray();
target = bytesToBitmap( result );
if ( listener != null ) {
listener.onCompressSuccess( result );
}
} catch ( Exception e ) {
e.printStackTrace();
target = null;
if ( listener != null ) {
listener.onCompressFailed( "压缩失败" );
}
} finally {
IOUtils.closeSilently( bos );
}
return target;
}
public static Bitmap compressBitmap( Bitmap bitmap, int maxSize ) {
if ( bitmap == null ) {
return null;
}
ByteArrayOutputStream bos = null;
Bitmap target = null;
try {
bos = new ByteArrayOutputStream();
int quality = 100;
do {
bos.reset();
bitmap.compress( Bitmap.CompressFormat.JPEG, quality, bos );
}
while ( bos.size() / 1024 > maxSize && ( quality -= 5 ) >= 0 );
byte[] result = bos.toByteArray();
target = bytesToBitmap( result );
} catch ( Exception e ) {
e.printStackTrace();
target = null;
} finally {
IOUtils.closeSilently( bos );
}
return target;
}
/**
* Decode an immutable bitmap from the specified byte array.
*
* @param b byte array of compressed image data
* @return an immutable bitmap or null in case of exception.
*/
public static Bitmap bytesToBitmap( byte[] b ) {
if ( b != null && b.length != 0 ) {
return BitmapFactory.decodeByteArray( b, 0, b.length );
} else {
return null;
}
}
/**
* Decode an immutable bitmap from the specified byte array.
*
* @param b byte array of compressed image data
* @param options Options that control downsampling and whether the
* image should be completely decoded, or just is size returned.
* @return an immutable bitmap or null in case of exception.
*/
public static Bitmap bytesToBitmap( byte[] b, BitmapFactory.Options options ) {
if ( b.length != 0 ) {
return BitmapFactory.decodeByteArray( b, 0, b.length, options );
} else {
return null;
}
}
/**
* Get max supported image size which will differ from different devices.
*
* @return max size related to the device.
*/
public static int getMaxSupportedImageSize() {
int textureLimit = getMaxTextureSize();
if ( textureLimit == 0 ) {
return SIZE_DEFAULT;
} else {
return Math.min( textureLimit, SIZE_LIMIT );
}
}
public static int getMaxTextureSize2() {
// The OpenGL texture size is the maximum size that can be drawn in an ImageView
int[] maxSize = new int[1];
GLES10.glGetIntegerv( GLES10.GL_MAX_TEXTURE_SIZE, maxSize, 0 );
return maxSize[0];
}
/**
* Decode a bitmap's input stream to find a proper inSampleSize according to device's max supported size.
*
* @param is bitmap's data source
* @param close whether to close input stream after work is done.
* @return a proper inSampleSize
*/
public static int findProperInSampleSize( InputStream is, boolean close ) {
// Just decode image size into options
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream( is, null, options );
} catch ( Exception e ) {
e.printStackTrace();
} finally {
if ( close ) IOUtils.closeSilently( is );
}
int maxSize = getMaxSupportedImageSize();
int sampleSize = 1;
while ( options.outHeight / sampleSize > maxSize || options.outWidth / sampleSize > maxSize ) {
sampleSize = sampleSize << 1;
}
Log.i( TAG, "sample size is " + sampleSize );
return sampleSize;
}
/**
* Read a picture's degree from a file.
*
* @param file data source of a picture
* @return degrees range from 0 to 360
*/
public static int readPictureDegree( File file ) {
return readPictureDegree( file.getAbsolutePath() );
}
/**
* Read a picture's degree from a file, we use {@link ExifInterface} instead of {@link ExifInterface}
* to avoid some unexpected bugs.
*
* @param filePath file's absolute path which we can read data source of a picture from.
* @return degrees range from 0 to 360
*/
public static int readPictureDegree( String filePath ) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface( filePath );
int orientation = exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL );
switch ( orientation ) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch ( Exception e ) {
e.printStackTrace();
}
Log.i( TAG, "ExifInterface, degree is " + degree );
return degree;
}
/**
* Rotate an bitmap to a specific angle.
*
* @param angle target angle
* @param bitmap data source
* @return Returns an immutable bitmap from subset of the source bitmap,
* transformed by the optional matrix. The new bitmap may be the
* same object as source, or a copy may have been made. It is
* initialized with the same density as the original bitmap.
* <p>
* If the source bitmap is immutable and the requested subset is the
* same as the source bitmap itself, then the source bitmap is
* returned and no new bitmap is created.
*/
public static Bitmap rotateBitmap( int angle, Bitmap bitmap ) {
if ( bitmap == null ) {
return null;
}
try {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preRotate( angle );
return Bitmap.createBitmap( bitmap, 0, 0, width, height, matrix, true );
} catch ( Exception e ) {
e.printStackTrace();
return bitmap;
}
}
/**
* Get picture's absolute path according to its uri.
*
* @param context context
* @param uri picture's uri
* @return absolute path of uri.
*/
public static String getRealPathFromUri( Context context, Uri uri ) {
int sdkVersion = Build.VERSION.SDK_INT;
if ( sdkVersion >= 19 ) {
return getRealPathFromUriAboveApi19( context, uri );
} else {
return getRealPathFromUriBelowAPI19( context, uri );
}
}
/**
* Create a default {@link BitmapFactory.Options} .
* Note this options use rgb_565 and a proper inSampleSize in order to save memory.
*
* @param is data source of picture
* @param close whether to close data source
* @return options containing rgb_565 config and a proper inSampleSize.
*/
public static BitmapFactory.Options newDefaultOptions( InputStream is, boolean close ) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inSampleSize = BitmapHelper.findProperInSampleSize( is, close );
return options;
}
/**
* Save picture to local file.
*
* @param bitmap data source
* @param file local file to store picture.
*/
public static void savePicture( Bitmap bitmap, File file ) {
final long start = System.currentTimeMillis();
if ( bitmap == null || file == null ) {
Log.i( TAG, "保存失败, bitmap or file is null." );
return;
}
if ( file.getParentFile() != null && !file.getParentFile().exists() ) {
file.getParentFile().mkdirs();
}
try {
final FileOutputStream fos = new FileOutputStream( file );
bitmap.compress( Bitmap.CompressFormat.JPEG, 100, fos );
fos.flush();
fos.close();
if ( file.exists() ) {
Log.i( TAG, "保存成功" );
}
} catch ( Exception e ) {
e.printStackTrace();
}
Log.i( TAG, "saving picture costs " + ( System.currentTimeMillis() - start ) + "ms" );
}
/**
* 适配api19以下(不包括api19),根据uri获取图片的绝对路径
*
* @param context 上下文对象
* @param uri 图片的Uri
* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
private static String getRealPathFromUriBelowAPI19( Context context, Uri uri ) {
return getDataColumn( context, uri, null, null );
}
/**
* 适配api19及以上,根据uri获取图片的绝对路径
*
* @param context 上下文对象
* @param uri 图片的Uri
* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
@SuppressLint( "NewApi" )
private static String getRealPathFromUriAboveApi19( Context context, Uri uri ) {
String filePath = null;
try {
// 如果是document类型的 uri, 则通过document id来进行处理
if ( DocumentsContract.isDocumentUri( context, uri ) ) {
String documentId = DocumentsContract.getDocumentId( uri );
if ( isMediaDocument( uri ) ) {
// 使用':'分割
String id = documentId.split( ":" )[1];
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = {id};
filePath = getDataColumn( context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs );
} else if ( isDownloadsDocument( uri ) ) {
Uri contentUri = ContentUris.withAppendedId( Uri.parse( "content://downloads/public_downloads" ), Long.valueOf( documentId ) );
filePath = getDataColumn( context, contentUri, null, null );
}
} else if ( "content".equalsIgnoreCase( uri.getScheme() ) ) {
filePath = getDataColumn( context, uri, null, null );
} else if ( "file".equals( uri.getScheme() ) ) {
filePath = uri.getPath();
}
} catch ( Exception e ) {
e.printStackTrace();
}
return filePath;
}
/**
* 获取数据库表中的 _data 列即返回Uri对应的文件路径
*/
private static String getDataColumn( Context context, Uri uri, String selection, String[] selectionArgs ) {
String path = null;
String[] projection = new String[]{MediaStore.Images.Media.DATA};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query( uri, projection, selection, selectionArgs, null );
if ( cursor != null && cursor.moveToFirst() ) {
int columnIndex = cursor.getColumnIndexOrThrow( projection[0] );
path = cursor.getString( columnIndex );
}
} catch ( Exception e ) {
if ( cursor != null ) {
cursor.close();
cursor = null;
}
} finally {
if ( cursor != null ) {
cursor.close();
cursor = null;
}
}
return path;
}
/**
* @param uri the Uri to check
* @return Whether the Uri authority is MediaProvider
*/
private static boolean isMediaDocument( Uri uri ) {
return "com.android.providers.media.documents".equals( uri.getAuthority() );
}
/**
* @param uri the Uri to check
* @return Whether the Uri authority is DownloadsProvider
*/
private static boolean isDownloadsDocument( Uri uri ) {
return "com.android.providers.downloads.documents".equals( uri.getAuthority() );
}
public static int getMaxTextureSize() {
try {
// Safe minimum default size
final int IMAGE_MAX_BITMAP_DIMENSION = SIZE_DEFAULT;
// Get EGL Display
EGL10 egl = ( EGL10 ) EGLContext.getEGL();
EGLDisplay display = egl.eglGetDisplay( EGL10.EGL_DEFAULT_DISPLAY );
// Initialise
int[] version = new int[2];
egl.eglInitialize( display, version );
// Query total number of configurations
int[] totalConfigurations = new int[1];
egl.eglGetConfigs( display, null, 0, totalConfigurations );
// Query actual list configurations
EGLConfig[] configurationsList = new EGLConfig[totalConfigurations[0]];
egl.eglGetConfigs( display, configurationsList, totalConfigurations[0], totalConfigurations );
int[] textureSize = new int[1];
int maximumTextureSize = 0;
// Iterate through all the configurations to located the maximum texture size
for ( int i = 0; i < totalConfigurations[0]; i++ ) {
// Only need to check for width since opengl textures are always squared
egl.eglGetConfigAttrib( display, configurationsList[i], EGL10.EGL_MAX_PBUFFER_WIDTH, textureSize );
// Keep trackCustomEvent of the maximum texture size
if ( maximumTextureSize < textureSize[0] )
maximumTextureSize = textureSize[0];
}
// Release
egl.eglTerminate( display );
// Return largest texture size found, or default
return Math.max( maximumTextureSize, IMAGE_MAX_BITMAP_DIMENSION );
} catch ( Exception e ) {
e.printStackTrace();
}
return 0;
}
public static String bitmapToBase64( Bitmap bitmap ) {
String result = null;
try {
if ( bitmap != null ) {
result = Base64.encodeToString( bitmapToBytes( bitmap ), Base64.DEFAULT );
}
} catch ( Exception e ) {
e.printStackTrace();
}
return result;
}
public static Bitmap base64ToBitmap( String base64Data ) {
byte[] bytes = Base64.decode( base64Data, Base64.DEFAULT );
return BitmapFactory.decodeByteArray( bytes, 0, bytes.length );
}
/**
* 在系统返回的intent中获取图片信息并转化为uri
*
* @param data
* @return
*/
public static Uri convertUri( Context context, Intent data ) {
if ( data == null || data.getData() == null ) {
return null;
}
Uri localUri = data.getData();
String scheme = localUri.getScheme();
String imagePath = "";
if ( "content".equals( scheme ) ) {
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = context.getContentResolver().query( localUri, filePathColumns, null, null, null );
if ( c != null ) {
c.moveToFirst();
int columnIndex = c.getColumnIndex( filePathColumns[0] );
imagePath = c.getString( columnIndex );
c.close();
}
} else if ( "file".equals( scheme ) ) {//小米4选择云相册中的图片是根据此方法获得路径
imagePath = localUri.getPath();
}
if ( TextUtils.isEmpty( imagePath ) ) {
return localUri;
}
Uri uri = Uri.fromFile( new File( imagePath ) );
return uri != null ? uri : localUri;
}
public static Bitmap colorToBitmap( Context context, int colorResId ) {// drawable 转换成bitmap
Bitmap.Config config = Bitmap.Config.ARGB_8888;// 取drawable的颜色格式
Bitmap bitmap = Bitmap.createBitmap( 1, 1, config );// 建立对应bitmap
bitmap.eraseColor( context.getResources().getColor( colorResId ) );
return bitmap;
}
public static String getAlphaHexValue( float alpha ) {
String color = Integer.toHexString( ( int ) alpha * 255 );
return TextUtils.isEmpty( color ) ? color : color.toUpperCase();
}
/**
* 抓取本地视频缩略图(操作可能耗时,尽量异步进行)
*
* @param filePath
* @return
*/
public static Bitmap getVideoThumbnail( String filePath ) {
Bitmap b = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
retriever.setDataSource(filePath, new HashMap<String, String>());
else
retriever.setDataSource(filePath);
// mediaMetadataRetriever.setDataSource(videoPath);
b = retriever.getFrameAtTime();
} catch ( IllegalArgumentException e ) {
e.printStackTrace();
} catch ( RuntimeException e ) {
e.printStackTrace();
} finally {
try {
retriever.release();
} catch ( RuntimeException e ) {
e.printStackTrace();
}
}
return b;
}
public interface OnCompressListener {
void onCompressSuccess( byte[] data );
void onCompressFailed( String msg );
void onBeforeCompress();
}
}

View File

@@ -1,6 +1,11 @@
package com.mogo.eagle.core.utilcode.util;
import android.graphics.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.FloatRange;
@@ -214,4 +219,159 @@ public final class ColorUtils {
public static boolean isLightColor(@ColorInt int color) {
return 0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color) >= 127.5;
}
/**
* ARGB颜色 转 HEX颜色
*/
public static String argbToHex(int alpha, int red, int green, int blue) {
if (alpha < 0 || alpha > 255
|| red < 0 || red > 255
|| green < 0 || green > 255
|| blue < 0 || blue > 255) {
return "";
}
String alphaStr = Integer.toHexString(alpha);
String redStr = Integer.toHexString(red);
String greenStr = Integer.toHexString(green);
String blueStr = Integer.toHexString(blue);
return ("#" + alphaStr + redStr + greenStr + blueStr).toUpperCase();
}
/**
* HEX颜色 转 ARGB颜色
*/
public static int[] hexToArgb(String hex) {
int[] rgb = new int[4];
if (!Pattern.matches("^#[0-9a-f[A-F]]{8}", hex)) {
return rgb;
}
String alphaStr = hex.substring(1, 3);
String redStr = hex.substring(3, 5);
String greenStr = hex.substring(5, 7);
String blueStr = hex.substring(7);
rgb[0] = Integer.valueOf(alphaStr, 16);
rgb[1] = Integer.valueOf(redStr, 16);
rgb[2] = Integer.valueOf(greenStr, 16);
rgb[3] = Integer.valueOf(blueStr, 16);
return rgb;
}
/**
* 对传入颜色生成梯度透明的颜色集合
*
* @param startColor 开始颜色
* @param startColor 结束颜色
* @param step 步长
* @return 生成的梯度颜色集合
*/
public static List<Integer> gradientAlpha(String startColor, String endColor, int step) {
// 将HEX转为RGB
int[] sColor = hexToArgb(startColor);
int[] eColor = hexToArgb(endColor);
// 计算每一步的差值
int aStep = (eColor[0] - sColor[0]) / step;
int rStep = (eColor[1] - sColor[1]) / step;
int gStep = (eColor[2] - sColor[2]) / step;
int bStep = (eColor[3] - sColor[3]) / step;
// 生成渐变色
List<Integer> gradientColorArr = new ArrayList<>();
for (int i = 0; i < step; i++) {
gradientColorArr.add(
Color.argb(aStep * i + sColor[0],
rStep * i + sColor[1],
gStep * i + sColor[2],
bStep * i + sColor[3]));
}
return gradientColorArr;
}
/**
* 对传入颜色生成梯度透明的颜色集合
*
* @param startColor 开始颜色
* @param startColor 结束颜色
* @param step 步长
* @return 生成的梯度颜色集合
*/
public static List<Integer> gradientAlpha_(String startColor, String centerColor, String endColor, int step) {
// 生成渐变色
List<Integer> gradientColorArr = new ArrayList<>();
// 将HEX转为RGB
int[] sColor = hexToArgb(startColor);
int[] cColor = hexToArgb(centerColor);
int[] eColor = hexToArgb(endColor);
if (step >= 3) {
int colorStep = (int) Math.floor(step/2);
// 计算每一步的差值
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;
for (int i = 0; i < colorStep; i++) {
gradientColorArr.add(
Color.argb((int)(aStep * i + sColor[0]),
(int)(rStep * i + sColor[1]),
(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;
for (int i = 0; i < colorStep; i++) {
gradientColorArr.add(
Color.argb((int)(aStep_ * i + cColor[0]),
(int)(rStep_ * i + cColor[1]),
(int)(gStep_ * i + cColor[2]),
(int)(bStep_ * i + cColor[3])));
}
} else {
gradientColorArr.add(Color.argb(cColor[0], cColor[1], cColor[2], cColor[3]));
}
return gradientColorArr;
}
/**
* 获取一组渐变色数组
*
* @param startColor 开始颜色
* @param endColor 结束颜色
* @param step 步长
* @return 生成的梯度颜色集合
*/
public static List<Integer> getGradientAlpha(String startColor, String centerColor, String endColor, int step) {
// 将HEX转为RGB
int[] sColor = hexToArgb(startColor);
int[] cColor = hexToArgb(centerColor);
int[] eColor = hexToArgb(endColor);
// 生成渐变色
List<Integer> gradientColorArr = new ArrayList<>();
if (step >= 3) {
// 开始颜色
gradientColorArr.add(Color.argb(sColor[0], sColor[1], sColor[2], sColor[3]));
// 中间颜色
for (int i = 0; i < (step - 2); i++) {
gradientColorArr.add(Color.argb(cColor[0], cColor[1], cColor[2], cColor[3]));
}
//结束颜色
gradientColorArr.add(Color.argb(eColor[0], eColor[1], eColor[2], eColor[3]));
} else {
gradientColorArr.add(Color.argb(cColor[0], cColor[1], cColor[2], cColor[3]));
}
return gradientColorArr;
}
}

View File

@@ -0,0 +1,689 @@
package com.mogo.eagle.core.utilcode.util;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class CommonUtils {
private static String mMacSerial = null;
private static String mCPUSerial = null;
private static boolean isMacSerialNoObtained = false;
private static boolean isCPUSerialNoObtained = false;
private static final Pattern VERSION_NAME_PATTERN = Pattern.compile("(\\d+\\.\\d+\\.\\d+)\\-*.*");
public static String getAndroidID(Context context) {
if (context == null) {
return "";
}
return Settings.Secure.getString(context.getContentResolver(), "android_id");
}
public static String getCPUSerialno() {
if (!TextUtils.isEmpty(mCPUSerial)) {
return mCPUSerial;
} else if (isCPUSerialNoObtained) {
mCPUSerial = "";
return mCPUSerial;
} else {
String str = "";
InputStreamReader ir = null;
LineNumberReader input = null;
try {
isCPUSerialNoObtained = true;
Process ex = Runtime.getRuntime().exec("cat /proc/cpuinfo");
if (ex == null) {
return null;
}
ir = new InputStreamReader(ex.getInputStream());
input = new LineNumberReader(ir);
while (null != str) {
str = input.readLine();
if (str != null) {
mCPUSerial = str.trim();
break;
}
}
} catch (IOException var4) {
var4.printStackTrace();
} finally {
if (ir != null) {
try {
ir.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return mCPUSerial;
}
}
public static int getVersionCode(Context context) {
if (context == null) {
return 1;
}
String pkgName = context.getPackageName();
try {
PackageInfo e = context.getPackageManager().getPackageInfo(pkgName, 0);
if (e != null) {
return e.versionCode;
}
} catch (Exception var2) {
var2.printStackTrace();
}
return 1;
}
public static String getMacSerialno() {
if (!TextUtils.isEmpty(mMacSerial)) {
return mMacSerial;
} else if (isMacSerialNoObtained) {
mMacSerial = "";
return mMacSerial;
} else {
String str = "";
InputStreamReader ir = null;
LineNumberReader input = null;
try {
isMacSerialNoObtained = true;
Process ex = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
if (ex == null) {
return null;
}
ir = new InputStreamReader(ex.getInputStream());
input = new LineNumberReader(ir);
while (null != str) {
str = input.readLine();
if (str != null) {
mMacSerial = str.trim();
break;
}
}
} catch (IOException var4) {
var4.printStackTrace();
} finally {
if (ir != null) {
try {
ir.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return mMacSerial;
}
}
/**
* 获取网络类型
*
* @return
*/
public static String getNetworkType(Context context) {
String name = "UNKNOWN";
try {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null) {
if (ConnectivityManager.TYPE_WIFI == networkInfo.getType()) {
return "WIFI";
}
}
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (tm == null) {
return name;
}
int type = tm.getNetworkType();
switch (type) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
name = "2G";
break;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
name = "3G";
break;
case TelephonyManager.NETWORK_TYPE_LTE:
name = "4G";
break;
// case TelephonyManager.NETWORK_TYPE_NR:
// name = "5G";
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
name = "UNKNOWN";
break;
default:
name = "UNKNOWN";
break;
}
} catch (Exception e) {
}
return name;
}
/**
* 得到手机的IMEI号
*
* @return
*/
public static String getIMEI(Context context) {
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null &&
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
return telephonyManager.getDeviceId();
}
} catch (Exception e) {
}
return "";
}
/**
* 得到手机的IMSI号
*
* @return
*/
public static String getIMSI(Context context) {
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
return telephonyManager.getSubscriberId();
}
} catch (Exception e) {
}
return "";
}
public static String checkSimState(Context context) {
String mString = "";
if (context == null) {
return mString;
}
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int simState = 0;
if (telephonyManager != null) {
simState = telephonyManager.getSimState();
}
switch (simState) {
case TelephonyManager.SIM_STATE_ABSENT:
mString = "无卡";
// do something
break;
case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
mString = "需要NetworkPIN解锁";
// do something
break;
case TelephonyManager.SIM_STATE_PIN_REQUIRED:
mString = "需要PIN解锁";
// do something
break;
case TelephonyManager.SIM_STATE_PUK_REQUIRED:
mString = "需要PUN解锁";
// do something
break;
case TelephonyManager.SIM_STATE_READY:
mString = "良好";
// do something
break;
case TelephonyManager.SIM_STATE_UNKNOWN:
mString = "未知状态";
// do something
break;
}
return mString;
}
/**
* 获取路由器Mac
*/
public static String getRouterMac(Context context) {
if (context == null) {
return "";
}
WifiManager wifi = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifi != null && wifi.getConnectionInfo() != null) {
return wifi.getConnectionInfo().getBSSID();
}
return "";
}
/**
* 获取wifi名字
*/
public static String getWifiName(Context context) {
if (context == null) {
return "";
}
WifiManager wifi = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifi != null && wifi.getConnectionInfo() != null) {
return wifi.getConnectionInfo().getSSID();
}
return "";
}
public static String getMobileIP(Context ctx) {
if (ctx == null) {
return "";
}
ConnectivityManager mConnectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);// 获取系统的连接服务
// 实例化mActiveNetInfo对象
NetworkInfo mActiveNetInfo = null;// 获取网络连接的信息
if (mConnectivityManager != null) {
mActiveNetInfo = mConnectivityManager.getActiveNetworkInfo();
}
if (mActiveNetInfo == null) {
return "";
} else {
return getIp(mActiveNetInfo);
}
}
// 显示IP信息
private static String getIp(NetworkInfo mActiveNetInfo) {
if (mActiveNetInfo == null) {
return "";
}
// 如果是WIFI网络
if (mActiveNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return getLocalIPAddress();
}
// 如果是手机网络
else if (mActiveNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return getLocalIPAddress();
} else {
return "";
}
}
// 获取本地IP函数
private static String getLocalIPAddress() {
try {
Enumeration<NetworkInterface> mEnumeration = NetworkInterface.getNetworkInterfaces();
if (mEnumeration != null) {
while (mEnumeration.hasMoreElements()) {
NetworkInterface intf = mEnumeration.nextElement();
if (intf != null && intf.getInetAddresses() != null) {
Enumeration<InetAddress> enumIPAddr = intf.getInetAddresses();
while (enumIPAddr.hasMoreElements()) {
InetAddress inetAddress = enumIPAddr.nextElement();
// 如果不是回环地址
if (inetAddress != null && !inetAddress.isLoopbackAddress()) {
// 直接返回本地IP地址
return inetAddress.getHostAddress();
}
}
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return "";
}
public static String getVersionName(Context context) {
return getVersionName(context, true);
}
public static String getVersionName(Context context, boolean fullVersionName) {
String appVersion = "";
try {
String packageName = context.getApplicationInfo().packageName;
appVersion = context.getPackageManager().getPackageInfo(packageName, 0).versionName;
if (!fullVersionName && appVersion != null && appVersion.length() > 0) {
Matcher matcher = VERSION_NAME_PATTERN.matcher(appVersion);
if (matcher.matches()) {
appVersion = matcher.group(1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return appVersion;
}
public static String getAppName(Context context) {
if (context == null) {
return "";
}
PackageManager pm = context.getPackageManager();
return context.getApplicationInfo().loadLabel(pm).toString();
}
public static String getModel() {
String temp = Build.MODEL;
return TextUtils.isEmpty(temp) ? "" : temp;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static long getLeftMemory(Context context) {
if (context == null) {
return -1;
}
if (Build.VERSION.SDK_INT >= 16) {
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
mActivityManager.getMemoryInfo(mi);
return (mi.totalMem - mi.availMem) / 1000;
}
return -1;
}
public static String encode(String string) {
try {
return URLEncoder.encode(string, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
public static String decode(String string) {
try {
return URLDecoder.decode(string, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
public static String getProcessName(Context context, int pid) {
try {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
if (processInfo.pid == pid) {
return processInfo.processName;
}
}
} catch (Exception e) {
}
return "";
}
public static int getStatusBarHeight(Context context) {
if (context == null) {
return 0;
}
int statusBarHeight = 0;
try {
Class c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);
} catch (Exception e) {
}
if (statusBarHeight > 0) {
return statusBarHeight;
}
try {
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
}
} catch (Exception e) {
}
return statusBarHeight;
}
/**
* 获取某个应用的版本名称
*
* @param context 应用上下文
* @param packageName 包名,如果为空,将获取 context 本身的版本名称
* @return
*/
public static String getVersionName(@NonNull Context context, @Nullable String packageName) {
try {
packageName = TextUtils.isEmpty(packageName) ? context.getPackageName() : packageName;
PackageManager packageManager = context.getPackageManager();
PackageInfo packInfo = packageManager.getPackageInfo(packageName, 0);
return packInfo.versionName;
} catch (Exception e) {
return "";
}
}
/**
* 获取某个应用的版本号
*
* @param context 应用上下文
* @param packageName 包名,如果为空,将获取 context 本身的版本号
* @return
*/
public static int getVersionCode(@NonNull Context context, @Nullable String packageName) {
try {
packageName = TextUtils.isEmpty(packageName) ? context.getPackageName() : packageName;
PackageManager packageManager = context.getPackageManager();
PackageInfo packInfo = packageManager.getPackageInfo(packageName, 0);
return packInfo.versionCode;
} catch (Exception e) {
return 0;
}
}
/**
* cpu
*/
public static double getCPU(String packageName) {
double Cpu = 0;
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("adb shell top -n 1| grep " + packageName);
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " + proc.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line + " ");
}
String str1 = stringBuffer.toString();
String str3 = str1.substring(str1.indexOf(packageName) - 43, str1.indexOf(packageName)).trim();
String cpu = str3.substring(0, 2);
cpu = cpu.trim();
Cpu = Double.parseDouble(cpu);
} catch (InterruptedException e) {
System.err.println(e);
} finally {
try {
proc.destroy();
} catch (Exception e2) {
}
}
} catch (Exception StringIndexOutOfBoundsException) {
System.out.println("请检查设备是否连接");
}
return Cpu;
}
/**
* 电量
*/
public static float getBattery(Context context) {
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, filter);
//当前剩余电量
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
//电量最大值
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
//电量百分比
float batteryPct = level / (float) scale;
return batteryPct;
}
/**
* 内存占比
*
* @param packageName 包名
* @return
*/
public static double getMemory(String packageName) {
double Heap = 0;
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("adb shell dumpsys meminfo " + packageName);
try {
if (process.waitFor() != 0) {
System.err.println("exit value = " + process.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line + " ");
}
String str1 = stringBuffer.toString();
String str2 = str1.substring(str1.indexOf("Objects") - 60, str1.indexOf("Objects"));
String str3 = str2.substring(0, 10);
str3 = str3.trim();
Heap = Double.parseDouble(str3) / 1024;
DecimalFormat df = new DecimalFormat("#.000");
String memory = df.format(Heap);
Heap = Double.parseDouble(memory);
} catch (InterruptedException e) {
System.err.println(e);
} finally {
try {
process.destroy();
} catch (Exception e2) {
}
}
} catch (Exception StringIndexOutOfBoundsException) {
System.out.print("请检查设备是否连接");
}
return Heap;
}
}

View File

@@ -0,0 +1,151 @@
/*
* Copyright (C) 2008 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.eagle.core.utilcode.util;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
/**
* Schedule a countdown until a time in the future, with
* regular notifications on intervals along the way.
*
* Example of showing a 30 second countdown in a text field:
*
* <pre class="prettyprint">
* new CountDownTimer(30000, 1000) {
*
* public void onTick(long millisUntilFinished) {
* mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
* }
*
* public void onFinish() {
* mTextField.setText("done!");
* }
* }.start();
* </pre>
*
* The calls to {@link #onTick(long)} are synchronized to this object so that
* one call to {@link #onTick(long)} won't ever occur before the previous
* callback is complete. This is only relevant when the implementation of
* {@link #onTick(long)} takes an amount of time to execute that is significant
* compared to the countdown interval.
*/
public abstract class CountDownTimer {
/**
* Millis since epoch when alarm should stop.
*/
private final long mMillisInFuture;
/**
* The interval in millis that the user receives callbacks
*/
private final long mCountdownInterval;
private long mStopTimeInFuture;
/**
* boolean representing if the timer was cancelled
*/
private boolean mCancelled = false;
/**
* @param millisInFuture The number of millis in the future from the call
* to {@link #start()} until the countdown is done and {@link #onFinish()}
* is called.
* @param countDownInterval The interval along the way to receive
* {@link #onTick(long)} callbacks.
*/
public CountDownTimer(long millisInFuture, long countDownInterval) {
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
}
/**
* Cancel the countdown.
*/
public synchronized final void cancel() {
mCancelled = true;
mHandler.removeMessages(MSG);
}
/**
* Start the countdown.
*/
public synchronized final CountDownTimer start() {
mCancelled = false;
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
return this;
}
/**
* Callback fired on regular interval.
* @param millisUntilFinished The amount of time until finished.
*/
public abstract void onTick(long millisUntilFinished);
/**
* Callback fired when the time is up.
*/
public abstract void onFinish();
private static final int MSG = 1;
// handles counting down
private Handler mHandler = new Handler() {
@Override
public void handleMessage( Message msg) {
synchronized (CountDownTimer.this) {
if (mCancelled) {
return;
}
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisLeft <= 0) {
onFinish();
} else if (millisLeft < mCountdownInterval) {
// no tick, just delay until done
sendMessageDelayed(obtainMessage(MSG), millisLeft);
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft);
// take into account user's onTick taking time to execute
long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();
// special case: user's onTick took more than interval to
// complete, skip to next interval
while (delay < 0) delay += mCountdownInterval;
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
}

View File

@@ -0,0 +1,452 @@
package com.mogo.eagle.core.utilcode.util;
import android.text.TextUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;
public class DateTimeUtils {
public static final int DATETIME_FIELD_REFERSH = 10; // 刷新时间(分钟),
//
public static final long ONE_SECOND = 1000L;
public static final long ONE_MINUTE = ONE_SECOND * 60L;
public static final long ONE_HOUR = ONE_MINUTE * 60L;
public static final long ONE_DAY = ONE_HOUR * 24L;
public static final long ONE_MONTH = ONE_DAY * 24L;
public static final long ONE_YEAR = ONE_MONTH * 24L;
// 下面的pattern在print和parse时都可以使用
public static final String MM_Yue_dd_Ri = "MM月dd日";
public static final String MM_Yue_dd_Ri_HH_mm = "MM月dd日 HH:mm";
public static final String M_Yue_d_Ri = "M月d日";
public static final String d_Ri = "d日";
public static final String yyyyMMdd = "yyyyMMdd";
public static final String yyyy_MM_dd = "yyyy-MM-dd";
public static final String yyyy_MM = "yyyy-MM";
public static final String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";
public static final String yyyy_MM_dd_HH_mm = "yyyy-MM-dd HH:mm";
public static final String yyyyMMddHHmmss = "yyyyMMddHHmmss";
public static final String HH_mm = "HH:mm";
public static final String yyyy_Nian_MM_Yue_dd_Ri = "yyyy年MM月dd日";
public static final String yyyy_Nian_MM_Yue = "yyyy年MM月";
public static final String MM_yy = "MM/yy";
public static final String dd_MM = "dd/MM";
public static final String MM_dd = "MM-dd";
private static final String pattern2 = "MM 月 dd";
// 下面的pattern是print时用parse时不应使用只有时间没有日期
public static final String HH_mm_ss = "HH:mm:ss";
private static final String[] PATTERNS = {yyyy_MM_dd_HH_mm_ss, yyyy_MM_dd_HH_mm, yyyy_MM_dd, yyyyMMdd};
public static Calendar cleanCalendarTime( Calendar c) {
c.set( Calendar.HOUR_OF_DAY, 0);
c.set( Calendar.MINUTE, 0);
c.set( Calendar.SECOND, 0);
c.set( Calendar.MILLISECOND, 0);
return c;
}
/**
* 获得指定日期表示格式转换成Calendar的格式
*
* @param src
* @param fallback 若无法转换,返回一个默认值
* @return
*/
public static <T> Calendar getCalendar( T src, Calendar fallback) {
if (src != null) {
try {
return getCalendar(src);
} catch ( Exception e) {
}
}
return ( Calendar ) fallback.clone();
}
/**
* 获得日期类型
*
* @param src 任何可以表示时间的类型目前支持Calendar,Date,long,String
* @return Calendar类型表示的时间
* @throws IllegalArgumentException
*/
public static <T> Calendar getCalendar( T src) {
Calendar calendar = Calendar.getInstance();
calendar.setLenient(false);
if (src == null) {
return null;
} else if (src instanceof Calendar ) {
calendar.setTimeInMillis((( Calendar ) src).getTimeInMillis());
} else if (src instanceof Date ) {
calendar.setTime(( Date ) src);
} else if (src instanceof Long ) {
calendar.setTimeInMillis(( Long ) src);
} else if (src instanceof String ) {
String nSrc = ( String ) src;
if ( TextUtils.isEmpty(nSrc)) {
return null;
}
try {
// 直接匹配的时候不能匹配到月份或日期不是2位数的情况
if ( Pattern.compile("\\d{4}年\\d{1,2}月\\d{1,2}日").matcher(nSrc).find()) {
nSrc = fixDateString(nSrc);
return getCalendarByPattern(nSrc, yyyy_MM_dd);
}
return getCalendarByPatterns(nSrc, PATTERNS);
} catch ( Exception e) {
try {
calendar.setTimeInMillis( Long.valueOf(nSrc));
} catch ( NumberFormatException e1) {
throw new IllegalArgumentException(e1);
}
}
} else {
throw new IllegalArgumentException();
}
return calendar;
}
/**
* YYYY年MM月DD日 --> YYYY-MM-DD
*/
private static String fixDateString( String date) {
if ( TextUtils.isEmpty(date)) {
return date;
}
String[] dateArray = date.split("[年月日]");
if (dateArray.length == 1) {
dateArray = date.split("-");
}
for (int i = 0; i < 3; i++) {
if (dateArray[i].length() == 1) {
dateArray[i] = "0" + dateArray[i];
}
}
return dateArray[0] + "-" + dateArray[1] + "-" + dateArray[2];
}
/**
* 匹配pattern获得时间若无法解析抛出异常
*
* @param dateTimeStr
* @param patternStr
* @return
* @throws IllegalArgumentException
*/
public static Calendar getCalendarByPattern( String dateTimeStr, String patternStr) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(patternStr, Locale.US);
sdf.setLenient(false);
Date d = sdf.parse(dateTimeStr);
Calendar c = Calendar.getInstance();
c.setLenient(false);
c.setTimeInMillis(d.getTime());
return c;
} catch ( Exception e) {
throw new IllegalArgumentException(e);
}
}
/**
* 匹配pattern数组中的所有pattern解析时间格式若没有可以解析的方式则抛出异常
*
* @param dateTimeStr
* @param patternStr
* @return
* @throws IllegalArgumentException
*/
public static Calendar getCalendarByPatterns( String dateTimeStr, String[] patternStr) {
for ( String string : patternStr) {
try {
return getCalendarByPattern(dateTimeStr, string);
} catch ( Exception e) {
}
}
throw new IllegalArgumentException();
}
/**
* 是否有服务器时间
*/
public static boolean hasServerTime;
/**
* 本地时间和服务器时间的间隔 time server local gap millis
*/
public static long tslgapm;
/**
* 本地时间和服务器时间的间隔 time server string
*/
public static String tss;
/**
* 获取与服务器时间矫正过的当前时间
*/
public static Calendar getCurrentDateTime() {
Calendar now = Calendar.getInstance();
now.setLenient(false);
if (hasServerTime) {
now.setTimeInMillis(now.getTimeInMillis() + tslgapm);
}
return now;
}
public static Calendar getCurrentDate() {
return cleanCalendarTime(getCurrentDateTime());
}
public static long getCurTimeInMillis(){
return System.currentTimeMillis();
}
/**
* login时server的日期
*
* @return
*/
public static Calendar getLoginServerDate() {
return getCalendar(tss);
}
/**
* 获得基准日期增加间隔天
*/
public static Calendar getDateAdd( Calendar start, int interval) {
if (start == null) {
return null;
}
Calendar c = ( Calendar ) start.clone();
c.add( Calendar.DATE, interval);
return c;
}
/**
* 获得时间间隔
*
* @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) {
return 0;
}
return Math.abs(from.getTimeInMillis() - to.getTimeInMillis()) / unit;
}
/**
* 获得日期间隔 忽略小时
*
* @param startdate
* @param enddate
* @return
*/
public static int getIntervalDays( String startdate, String enddate, String pattern) {
int betweenDays = 0;
if (startdate == null || enddate == null) {
return betweenDays;
}
Calendar d1 = getCalendarByPattern(startdate, pattern);
Calendar d2 = getCalendarByPattern(enddate, pattern);
return getIntervalDays(d1, d2);
}
public static <T> 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);
}
private static String[] weekdays = {"", "周日", "周一", "周二", "周三", "周四", "周五", "周六",};
private static String[] weekdays1 = {"", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六",};
/**
* calendar --> 周一~周日
*/
public static String getWeekDayFromCalendar( Calendar cal) {
if (cal == null) {
throw new IllegalArgumentException();
}
return weekdays[cal.get( Calendar.DAY_OF_WEEK)];
}
/**
* calendar --> 星期日~星期六
*/
public static String getWeekDayFromCalendar1( Calendar cal) {
if (cal == null) {
throw new IllegalArgumentException();
}
return weekdays1[cal.get( Calendar.DAY_OF_WEEK)];
}
/**
* 判断是否是闰年 这个方法不要改动!
*
* @param date(2009-10-13 || 2009年10月13日 || 2009)
* @return true 是 false 不是
*/
public static boolean isLeapyear( String date) {
Calendar calendar = getCalendar(date);
if (calendar != null) {
int year = calendar.get( Calendar.YEAR);
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
return false;
}
// 是否到刷新时间
public static boolean isRefersh(long beforeTime) {
return isRefersh(DATETIME_FIELD_REFERSH * 1000 * 60, beforeTime);
}
// 是否到刷新时间
public static boolean isRefersh(long gap, long beforeTime) {
return new Date().getTime() - beforeTime >= gap;
}
public static String printCalendarByPattern( Calendar c, String patternStr) {
if (null == c || null == patternStr) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(patternStr, Locale.US);
sdf.setLenient(false);
return sdf.format(c.getTime());
}
/**
* 只通过年月日比较两个Calendar
*
* @return c1 < c2 = -1 ; c1 > c2 = 1 ; c1 == c2 = 0
*/
public static int compareCalendarIgnoreTime( Calendar c1, Calendar c2) {
if (c1.get( Calendar.YEAR) > c2.get( Calendar.YEAR)) {
return 1;
} else if (c1.get( Calendar.YEAR) < c2.get( Calendar.YEAR)) {
return -1;
} else {
if (c1.get( Calendar.MONTH) > c2.get( Calendar.MONTH)) {
return 1;
} 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;
}
}
}
}
public static void setTimeWithHHmm( Calendar src, String HH_mm) {
if ( TextUtils.isEmpty(HH_mm) || null == src) {
return;
}
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]));
} catch ( NumberFormatException e) {
}
}
public static int getDayDiff(long time1, long time2) {
Date dateA = new Date(time1);
Date dateB = new Date(time2);
Calendar calDateA = Calendar.getInstance();
calDateA.setTime(dateA);
Calendar calDateB = Calendar.getInstance();
calDateB.setTime(dateB);
if (calDateA.get( Calendar.YEAR) == calDateB.get( Calendar.YEAR)
&& calDateA.get( Calendar.MONTH) == calDateB.get( Calendar.MONTH)) {
return calDateB.get( Calendar.DAY_OF_MONTH) - calDateA.get( Calendar.DAY_OF_MONTH);
} else if (calDateA.get( Calendar.YEAR) == calDateB.get( Calendar.YEAR) && ((calDateB.get( Calendar.MONTH) - calDateA.get( Calendar.MONTH)) == 1
|| (calDateB.get( Calendar.MONTH) - calDateA.get( Calendar.MONTH)) == -11)) {//处理跨年情况
return calDateB.get( Calendar.DAY_OF_MONTH) + (getCurrentMonthLastDay() - calDateA.get( Calendar.DAY_OF_MONTH));
}
return 0;
}
public static int getCurrentMonthLastDay() {
Calendar a = Calendar.getInstance();
a.set( Calendar.DATE, 1);
a.roll( Calendar.DATE, -1);
int maxDate = a.get( Calendar.DATE);
return maxDate;
}
public static String convertToChineseWeekNumber( int number) {
switch (number) {
case 1:
return "";
case 2:
return "";
case 3:
return "";
case 4:
return "";
case 5:
return "";
case 6:
return "";
case 0:
return "";
default:
return "";
}
}
/**
* 获取分钟数
*/
private static int getMinutes( String str, int blankCount) {
int ret = 0;
if (str.split(" ").length < (blankCount + 1)) {
return ret;
}
String hh_mm = str.split(" ")[blankCount];
String s = "";
if (!TextUtils.isEmpty(hh_mm) && hh_mm.length() >= 4) {
s = hh_mm.substring(3);
}
try {
ret = Integer.parseInt(s);
} catch ( NumberFormatException e) {
e.printStackTrace();
}
return ret;
}
/**
* 获取 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;
}
}

View File

@@ -0,0 +1,110 @@
package com.mogo.eagle.core.utilcode.util;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.elegant.utils.storage.SharedPrefsMgr;
import androidx.core.content.ContextCompat;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public final class DeviceIdUtils {
public static final String KEY_DEVICE_ID = "deviceId";
private DeviceIdUtils() {}
private static void saveDeviceId( Context context, String deviceId){
SharedPrefsMgr.getInstance(context).putString(KEY_DEVICE_ID, deviceId);
}
public static String getDeviceId( Context context) {
if(context == null){
throw new NullPointerException("context must not be null.");
}
final Context appContext = context.getApplicationContext();
String deviceId = SharedPrefsMgr.getInstance( context ).getString( KEY_DEVICE_ID );
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 {
deviceId = ((TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber();
}
if (TextUtils.isEmpty(deviceId)) {
deviceId = getDeviceSerial();
if (TextUtils.isEmpty(deviceId) || deviceId.equalsIgnoreCase("unknown")) {
deviceId = getAndroidId(appContext);
if (TextUtils.isEmpty(deviceId)) {
deviceId = String.valueOf(System.currentTimeMillis());
}
}
}
}
saveDeviceId(appContext,deviceId);
}
return deviceId;
}
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;
}
}
TelephonyManager telephonymanager = ( TelephonyManager ) context.getSystemService( Context.TELEPHONY_SERVICE);
if (telephonymanager != null) {
id = telephonymanager.getDeviceId();
if ( TextUtils.isEmpty(id))
id = "";
}
return id;
}
private static String getAndroidId( Context context) {
String s = "";
s = Settings.Secure.getString(context.getContentResolver(), "android_id");
if ( TextUtils.isEmpty(s))
s = "";
return s;
}
private static String getDeviceSerial() {
String serial = "unknown";
try {
Class clazz = Class.forName("android.os.Build");
Class paraTypes = Class.forName("java.lang.String");
Method method = clazz.getDeclaredMethod("getString", paraTypes);
if (!method.isAccessible()) {
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) {
e.printStackTrace();
}
return serial;
}
}

View File

@@ -1,20 +1,28 @@
package com.mogo.eagle.core.utilcode.util;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.os.Build;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.security.DigestInputStream;
import java.security.MessageDigest;
@@ -26,6 +34,9 @@ import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import androidx.annotation.IntRange;
import androidx.core.content.FileProvider;
/**
* <pre>
* author: Blankj
@@ -1446,6 +1457,389 @@ public final class FileUtils {
return blockSize * availableSize;
}
public static boolean createFileDir(String fileDir) {
if (TextUtils.isEmpty(fileDir)) {
return false;
}
try {
File dir = new File(fileDir);
if(!dir.exists()){
return dir.mkdirs();
}
return dir.exists();
} catch (Exception e) {
return false;
}
}
public static boolean createFileDir(File dir) {
if (dir == null) {
return false;
}
try {
return dir.exists() || dir.mkdir();
} catch (Exception e) {
return false;
}
}
public static void writeToFile(String fileDir, String fileName, String content) {
if (fileDir == null || fileName == null || content == null) {
return;
}
if (!createFileDir(fileDir)) {
return;
}
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try {
fos = new FileOutputStream(fileDir + fileName, true);
osw = new OutputStreamWriter(fos);
osw.write(content);
osw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeSilently(fos);
IOUtils.closeSilently(osw);
}
}
/**
* Read a text file into a String, optionally limiting the length.
*/
public static String readTextFile(File file) {
InputStream is = null;
BufferedInputStream bis = null;
ByteArrayOutputStream bos = null;
String text = null;
try {
is = new FileInputStream(file);
bis = new BufferedInputStream(is);
bos = new ByteArrayOutputStream();
int len;
byte[] data = new byte[1024];
do {
len = bis.read(data);
if (len > 0) bos.write(data, 0, len);
} while (len == data.length);
text = bos.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeSilently(is);
IOUtils.closeSilently(bis);
IOUtils.closeSilently(bos);
}
return text;
}
public static String fileToBase64(File file) {
String base64 = null;
InputStream in = null;
try {
in = new FileInputStream(file);
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 {
IOUtils.closeSilently(in);
}
return base64;
}
/**
* Writes string to file. Basically same as "echo -n $string > $filename"
*/
public static void stringToFile(String filename, String string) {
FileWriter out = null;
try {
out = new FileWriter(filename);
out.write(string);
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeSilently(out);
}
}
public static InputStream stringToStream(String content) {
InputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(content.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return inputStream;
}
public static String streamToString(InputStream is) throws IOException {
String content = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1) {
bos.write(i);
}
content = bos.toString();
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
public static String getStringFromFile(Context context, String fileName) {
FileInputStream fis = null;
ByteArrayOutputStream os = null;
String content = null;
try {
fis = context.openFileInput(fileName);
os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fis.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
content = os.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeSilently(fis);
IOUtils.closeSilently(os);
}
return content;
}
public static InputStream getStreamFromFile(Context context, String fileName) {
FileInputStream fis = null;
try {
fis = context.openFileInput(fileName);
} catch (Exception e) {
e.printStackTrace();
}
return fis;
}
public static void saveStringToFile(Context context, String content, String fileName) {
try {
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(content.getBytes());
IOUtils.closeSilently(fos);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将scheme为file的uri转成FileProvider 提供的content uri
*/
public static Uri convertFileUriToFileProviderUri(Context context, Uri uri) {
if (uri == null) return null;
if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
return getUriForFile(context, new File(uri.getPath()));
}
return uri;
}
/**
* 创建一个用于拍照图片输出路径的Uri (FileProvider)
*/
public static Uri getUriForFile(Context context, File file) {
return FileProvider.getUriForFile(context, getFileProviderName(context), file);
}
public static String getFileProviderName(Context context) {
return context.getPackageName() + ".fileprovider";
}
/**
* 把Uri 解析出文件绝对路径
*/
public static String parseOwnUri(Context context, Uri uri) {
if (uri == null) return null;
String path;
if (TextUtils.equals(uri.getAuthority(), getFileProviderName(context))) {
path = new File(uri.getPath()).getAbsolutePath();
} else {
path = uri.getPath();
}
return path;
}
public static String getFileStreamPath(Context context, String name) {
String absFileName = null;
try {
File file = context.getFileStreamPath(name);
if (file != null && file.exists()) {
absFileName = file.getAbsolutePath();
}
} catch (Exception e) {
e.printStackTrace();
}
return absFileName;
}
/**
* 拷贝文件数据到指定目录
*
* @param is
* @param to
* @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======");
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().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) {
if (listener != null) {
listener.onFail(e);
return;
}
}
if (listener != null) {
listener.onFinish(to);
}
}
}).start();
}
/**
* 拷贝文件到制定目录
*
* @param from
* @param to
* @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);
}
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 (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();
}
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) {
if (listener != null) {
listener.onFail(e);
return;
}
}
if (listener != null) {
listener.onFinish(to);
}
}
}).start();
}
/**
* 文件拷贝监听
*/
public interface FileCopyListener {
// 开始
void onStart();
// 失败
void onFail(Exception e);
// 进度
void onProcess(@IntRange(from = 0, to = 100) int process);
// 结束成功
void onFinish(String toPath);
}
///////////////////////////////////////////////////////////////////////////
// interface
///////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,49 @@
package com.mogo.eagle.core.utilcode.util;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;
import androidx.annotation.Nullable;
public class IOUtils {
public static byte[] inputToBytes( InputStream is) {
if(is == null){
return null;
}
ByteArrayOutputStream bos = null;
byte[] result = null;
try{
bos = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = is.read(buff, 0, 100)) > 0) {
bos.write(buff, 0, rc);
}
result = bos.toByteArray();
}catch ( Exception e){
e.printStackTrace();
result = null;
}finally {
closeSilently(bos);
}
return result;
}
public static void closeSilently(@Nullable Closeable c) {
if (c == null) return;
try {
c.close();
c = null;
} catch ( Throwable t) {
t.printStackTrace();
}
}
}

View File

@@ -0,0 +1,29 @@
package com.mogo.eagle.core.utilcode.util;
import android.content.Context;
import android.content.Intent;
/**
* @author congtaowang
* @since 2020-02-03
* <p>
* 描述
*/
public class LaunchUtils {
/**
* 通过包名启动app
*
* @param context
* @param pkg 包名
*/
public static void launchByPkg( Context context, String pkg ) throws Exception {
Intent intent = getLaunchIntentForPackage( context, pkg );
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
context.startActivity( intent );
}
public static Intent getLaunchIntentForPackage( Context context, String pkg ) {
return context.getPackageManager().getLaunchIntentForPackage( pkg );
}
}

View File

@@ -0,0 +1,398 @@
/*
* 创建日期2012-10-9
*/
package com.mogo.eagle.core.utilcode.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherUtils {
/**
* 匹配Email地址
*/
public static final String REGEX_EMAIL = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
/**
* 匹配:手机号码
*/
public static final String REGEX_MOBILE_NUMBER = "^[1][3-9]\\d{9}$";
/**
* 正则表达式中使用的特殊的计算符号,如:'$', '*', ...
*/
public static final char[] PATTERN_REGEX_SPECIAL_CHARACTERS = { '$', // 匹配输入字符串的结尾位置。如果设置了 RegExp 对象的 Multiline 属性,则 $ 也匹配 '\n' 或 '\r'。要匹配 $ 字符本身,请使用 \$。
'(', ')', // 标记一个子表达式的开始和结束位置。子表达式可以获取供以后使用。要匹配这些字符,请使用 \( 和 \)。
'*', // 匹配前面的子表达式零次或多次。要匹配 * 字符,请使用 \*。
'+', // 匹配前面的子表达式一次或多次。要匹配 + 字符,请使用 \+。
'.', // 匹配除换行符 \n之外的任何单字符。要匹配 .,请使用 \。
'[', // 标记一个中括号表达式的开始。要匹配 [,请使用 \[。
'?', // 匹配前面的子表达式零次或一次,或指明一个非贪婪限定符。要匹配 ? 字符,请使用 \?。
'\\', // 将下一个字符标记为或特殊字符、或原义字符、或向后引用、或八进制转义符。例如, 'n' 匹配字符 'n'。'\n' 匹配换行符。序列 '\\' 匹配 "\",而 '\(' 则匹配 "("。
'^', // 匹配输入字符串的开始位置,除非在方括号表达式中使用,此时它表示不接受该字符集合。要匹配 ^ 字符本身,请使用 \^。
'{', // 标记限定符表达式的开始。要匹配 {,请使用 \{。
'|', // 指明两项之间的一个选择。要匹配 |,请使用 \|。
};
/** 英文标点符号 */
private static final int TYPE_PUNCT = 1;
/** 数字 */
private static final int TYPE_DIGIT = 2;
/** 小写字母字符 */
private static final int TYPE_LOWER_LETTER = 3;
/** 大写字母字符 */
private static final int TYPE_UPPER_LETTER = 4;
/** 汉字字符串包括了中文标点符号 */
private static final int TYPE_CJK = 5;
/** 汉字字符串剔除了中文标点符号 */
private static final int TYPE_NO_PUNCTUATION_CJK = 6;
/** 是否是空白字符 */
private static final int TYPE_WHITESPACE = 7;
/** 不是字母 数字 英文标点符号 */
private static final int TYPE_NOT_PUNCT_DIGIT_LETTER = 8;
private static boolean isMatchesChar(int type, char ch) {
switch (type) {
case TYPE_PUNCT:
return isPunct(ch);
case TYPE_DIGIT:
return Character.isDigit(ch);
case TYPE_LOWER_LETTER:
return isLowerLetter(ch);
case TYPE_UPPER_LETTER:
return isUpperLetter(ch);
case TYPE_CJK:
return isCJK(ch);
case TYPE_NO_PUNCTUATION_CJK:
return isNoPunctuationCJK(ch);
case TYPE_WHITESPACE:
return Character.isWhitespace(ch);
case TYPE_NOT_PUNCT_DIGIT_LETTER:
return !( Character.isDigit(ch) || isLowerLetter(ch) || isUpperLetter(ch) || isPunct(ch));
default:
return false;
}
}
private static boolean isMatches(int type, String input) {
if (input != null && input.length() > 0) {
for (int i = input.length() - 1; i >= 0; i--) {
if (!isMatchesChar(type, input.charAt(i))) {
return false;
} else if (i == 0) {
return true;
}
}
}
return false;
}
private static boolean isMatchesInclude(int type, String input) {
if (input != null && input.length() > 0) {
for (int i = input.length() - 1; i >= 0; i--) {
if (isMatchesChar(type, input.charAt(i))) {
return true;
}
}
}
return false;
}
/**
* 匹配正则表达式
*
* @param regex
* @param input
* @return
*/
public static boolean isMatches( String regex, String input) {
return input == null ? false : Pattern.compile(regex).matcher(input).find();
}
/**
* 匹配正则表达式(忽略大小写)
*
* @param regex
* @param input
* @return
*/
public static boolean isMatchesIgnoreCase( String regex, String input) {
return input == null ? false : Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(input).find();
}
/**
* 是否是正则表达式中使用的特殊的计算符号,如:'$', '*', ...
*
* @param ch
* @return
*/
public static boolean isPatternRegexSpecialCharacter(char ch) {
for (int i = PATTERN_REGEX_SPECIAL_CHARACTERS.length - 1; i >= 0; i--) {
if (ch == PATTERN_REGEX_SPECIAL_CHARACTERS[i]) {
return true;
}
}
return false;
}
/**
* 是否是标点符号POSIX 字符类(仅 US-ASCII \p{Punct} 标点符号:!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
*
* @param ch
* @return
*/
public static boolean isPunct(char ch) {
return (ch >= 0x21 && ch <= 0x2F) // !"#$%&'()*+,-./
|| (ch >= 0x3A && ch <= 0x40) // :;<=>?@
|| (ch >= 0x5B && ch <= 0x60) // [\]^_`
|| (ch >= 0x7B && ch <= 0x7E);// {|}~
}
/**
* 是否是标点符号字符串 中文标点识别不了
*
* @param input
* @return
*/
public static boolean isPunct( String input) {
return isMatches(TYPE_PUNCT, input);
}
/**
* 是否包含标点符号字符串
*
* @param input
* @return
*/
public static boolean isIncludePunct( String input) {
return isMatchesInclude(TYPE_PUNCT, input);
}
/**
* 是否包含非字母数字以及Punct规定的字符串
*
* @param input
* @return 含有则返回true否则 返回false
*/
public static boolean isIncludeInvalidChar( String input) {
return isMatchesInclude(TYPE_NOT_PUNCT_DIGIT_LETTER, input);
}
/**
* 是否是数字字符串
*
* @param input
* @return
*/
public static boolean isDigit( String input) {
return isMatches(TYPE_DIGIT, input);
}
/**
* 是否包含数字字符串
*
* @param input
* @return
*/
public static boolean isIncludeDigit( String input) {
return isMatchesInclude(TYPE_DIGIT, input);
}
/**
* 是否是小写字母字符([a-z]
*
* @param ch
* @return
*/
public static boolean isLowerLetter(char ch) {
return ch >= 0x61 && ch <= 0x7A;
}
/**
* 是否是小写字母字符串([a-z]
*
* @param input
* @return
*/
public static boolean isLowerLetter( String input) {
return isMatches(TYPE_LOWER_LETTER, input);
}
/**
* 是否包含小写字母字符串([a-z]
*
* @param input
* @return
*/
public static boolean isIncludeLowerLetter( String input) {
return isMatchesInclude(TYPE_LOWER_LETTER, input);
}
/**
* 是否是大写字母字符([A-Z]
*
* @param ch
* @return
*/
public static boolean isUpperLetter(char ch) {
return ch >= 0x41 && ch <= 0x5A;
}
/**
* 是否是大写字母字符串([A-Z]
*
* @param
* @return
*/
public static boolean isUpperLetter( String input) {
return isMatches(TYPE_UPPER_LETTER, input);
}
/**
* 是否包含大写字母字符串([A-Z]
*
* @param input
* @return
*/
public static boolean isIncludeUpperLetter( String input) {
return isMatchesInclude(TYPE_UPPER_LETTER, input);
}
/**
* 是否是字母字符串([A-Za-z]
*
* @param ch
* @return
*/
public static boolean isLetter(char ch) {
return isLowerLetter(ch) || isUpperLetter(ch);
}
/**
* 是否是汉字字符(广义上的汉字字符,很多都无法用输入法输出的汉字)
*
* @param c
* @return
*/
public static boolean isCJK(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (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;
}
/**
* 是否是汉字字符(不包含标点)
*
* @param c
* @return
*/
public static boolean isNoPunctuationCJK(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (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
return true;
}
return false;
}
/**
* 是否是汉字字符(不包含标点)
*
* @param input
* @return
*/
public static boolean isNoPunctuationCJK( String input) {
return isMatches(TYPE_NO_PUNCTUATION_CJK, input);
}
/**
* 是否是汉字字符串(广义上的汉字字符,很多都无法用输入法输出的汉字)
*
* @param input
* @return
*/
public static boolean isCJK( String input) {
return isMatches(TYPE_CJK, input);
}
/**
* 是否包含汉字字符串(广义上的汉字字符,很多都无法用输入法输出的汉字)
*
* @param input
* @return
*/
public static boolean isIncludeCJK( String input) {
return isMatchesInclude(TYPE_CJK, input);
}
/**
* 是否是空白字符
*
* @param input
* @return
*/
public static boolean isWhitespace( String input) {
return isMatches(TYPE_WHITESPACE, input);
}
/**
* 是否包含空白字符
*
* @param input
* @return
*/
public static boolean isIncludeWhitespace( String input) {
return isMatchesInclude(TYPE_WHITESPACE, input);
}
/**
* 是否符合密码规则
*
* @param input
* @return
*/
public static boolean isFetionPassword( String input) {
// 密码必须含有字母和数字符号可选但是必须符合Punct标准,否则返回false
// 首先判断是否含有无效字符含有则返回false
if (isIncludeInvalidChar(input)) {
return false;
}
// 长度不符合要求,返回 false
if (input.length() < 6 || input.length() > 16) {
return false;
}
int tmpValue = 0;
if (isMatches("[A-Za-z]{1,15}", input)) {
tmpValue++;
}
if (isMatches("[0-9]{1,15}", input)) {
tmpValue++;
}
if (tmpValue >= 2) {
return true;
} else {
return false;
}
}
/**
* 1个或者多个0-9组成的数字
*
* @param str
* @return
*/
public static boolean isNumeric( String str) {
Pattern pattern = Pattern.compile("[0-9]+");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
}

View File

@@ -11,11 +11,14 @@ import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Formatter;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresPermission;
import java.lang.reflect.Method;
@@ -34,6 +37,8 @@ import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_NETWORK_STATE;
@@ -89,6 +94,116 @@ public final class NetworkUtils {
return info != null && info.isConnected();
}
/**
* Returns true if device is connected to wifi or mobile network, false
* otherwise.
*
* @param context
* @return
*/
public static boolean isConnected( Context context ) {
if ( context == null ) {
return false;
}
ConnectivityManager conMan = (ConnectivityManager) context
.getSystemService( Context.CONNECTIVITY_SERVICE );
if ( conMan == null ) {
return false;
}
NetworkInfo infoWifi = conMan.getNetworkInfo( ConnectivityManager.TYPE_WIFI );
if ( infoWifi != null ) {
NetworkInfo.State wifi = infoWifi.getState();
if ( wifi == NetworkInfo.State.CONNECTED ) {
return true;
}
}
NetworkInfo infoMobile = conMan.getNetworkInfo( ConnectivityManager.TYPE_MOBILE );
if ( infoMobile != null ) {
NetworkInfo.State mobile = infoMobile.getState();
if ( mobile == NetworkInfo.State.CONNECTED ) {
return true;
}
}
return false;
}
/**
* Check if there is any connectivity to a Wifi network
*
* @param context
* @return
*/
public static boolean isConnectedWifi( Context context ) {
if ( context == null ) {
return false;
}
NetworkInfo info = getNetworkInfo( context );
return ( info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI );
}
/**
* Check if there is any connectivity to a mobile network
*
* @param context
* @return
*/
public static boolean isConnectedMobile( Context context ) {
if ( context == null ) {
return false;
}
NetworkInfo info = getNetworkInfo( context );
return ( info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE );
}
/**
* Get the network info
*
* @param context
* @return
*/
@Nullable
public static NetworkInfo getNetworkInfo( Context context ) {
if ( context == null ) {
return null;
}
ConnectivityManager cm = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
if ( cm != null ) {
return cm.getActiveNetworkInfo();
}
return null;
}
/**
* URL
*
* @param url
* @return true false
*/
public static boolean isNetworkUrl( String url ) {
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
Pattern patt = Pattern.compile( regex );
Matcher matcher = patt.matcher( url );
return matcher.matches();
}
public static int netStrengthLevel = 0;
public static void listenNetStrength(Context context) {
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
manager.listen(new PhoneStateListener() {
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
netStrengthLevel = signalStrength.getLevel();
}
}, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
/**
* Return whether network is available.
* <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p>

View File

@@ -6,6 +6,7 @@ import android.app.Application;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.os.Process;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
@@ -16,7 +17,10 @@ import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
@@ -220,7 +224,7 @@ public final class ProcessUtils {
private static String getCurrentProcessNameByFile() {
try {
File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
File file = new File("/proc/" + Process.myPid() + "/" + "cmdline");
BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
@@ -237,7 +241,7 @@ public final class ProcessUtils {
if (am == null) return "";
List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
if (info == null || info.size() == 0) return "";
int pid = android.os.Process.myPid();
int pid = Process.myPid();
for (ActivityManager.RunningAppProcessInfo aInfo : info) {
if (aInfo.pid == pid) {
if (aInfo.processName != null) {
@@ -270,4 +274,74 @@ public final class ProcessUtils {
}
return processName;
}
public static boolean isMainProcess( Context context ) {
try {
ActivityManager activityManager = ( ( ActivityManager ) context.getSystemService( Context.ACTIVITY_SERVICE ) );
if ( activityManager == null ) {
return false;
}
List<ActivityManager.RunningAppProcessInfo> raps = activityManager.getRunningAppProcesses();
if ( raps == null || raps.size() <= 0 ) {
return false;
}
int pid = Process.myPid();
String packageName = context.getPackageName();
for ( ActivityManager.RunningAppProcessInfo info : raps ) {
if ( packageName.equals( info.processName ) ) {
return pid == info.pid;
}
}
return false;
} catch ( Exception e ) {
e.printStackTrace();
}
return false;
}
public static String getPackageName() {
String packageName = null;
BufferedReader reader = null;
try {
reader = new BufferedReader( new InputStreamReader( new FileInputStream( "/proc/" + Process.myPid() + "/cmdline" ) ) );
packageName = reader.readLine().trim();
} catch ( Exception e ) {
e.printStackTrace();
packageName = String.valueOf( Process.myPid() );
} finally {
if ( reader != null ) try {
reader.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
return packageName;
}
/**
* 获取进程号对应的进程名
*
* @param pid 进程号
* @return 进程名
*/
public static String getProcessName( int pid ) {
BufferedReader reader = null;
try {
reader = new BufferedReader( new FileReader( "/proc/" + pid + "/cmdline" ) );
String processName = reader.readLine();
if ( !TextUtils.isEmpty( processName ) ) {
processName = processName.trim();
}
return processName;
} catch ( Throwable t ) {
t.printStackTrace();
} finally {
IOUtils.closeSilently( reader );
}
return null;
}
}

View File

@@ -0,0 +1,121 @@
package com.mogo.eagle.core.utilcode.util;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class SoftKeyBoardJobber {
public static boolean hideIfNecessary( Activity context, MotionEvent ev ) {
if ( ev.getAction() == MotionEvent.ACTION_DOWN ) {
View v = context.getCurrentFocus();
if ( isShouldHideInput( v, ev ) ) {
InputMethodManager imm = ( InputMethodManager ) context.getSystemService( Context.INPUT_METHOD_SERVICE );
if ( imm != null ) {
imm.hideSoftInputFromWindow( v.getWindowToken(), 0 );
return true;
}
}
}
return false;
}
private static boolean isShouldHideInput( View v, MotionEvent event ) {
if ( v != null && ( v instanceof EditText ) ) {
int[] leftTop = {0, 0};
// 获取输入框当前的location位置
v.getLocationInWindow( leftTop );
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + v.getHeight();
int right = left + v.getWidth();
return !( event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom );
}
return false;
}
public static void hide( Context context, View v ) {
InputMethodManager imm = getInputMethodManager( context );
if ( imm != null ) {
imm.hideSoftInputFromWindow( v.getWindowToken(), 0 );
}
}
public static void show( Context context ) {
InputMethodManager imm = getInputMethodManager( context );
if ( imm != null ) {
imm.toggleSoftInput( 0, InputMethodManager.HIDE_NOT_ALWAYS );
}
}
private static InputMethodManager imm = null;
private static InputMethodManager getInputMethodManager( Context context ) {
if ( imm == null ) {
imm = ( InputMethodManager ) context.getSystemService( Context.INPUT_METHOD_SERVICE );
}
return imm;
}
public interface OnSoftKeyboardChangeListener {
void onSoftKeyBoardChange( int softKeyboardHeight, boolean visible );
}
public static ViewTreeObserver.OnGlobalLayoutListener observeSoftKeyboard( Activity activity, final OnSoftKeyboardChangeListener listener ) {
if ( !isAliveActivity( activity ) || listener == null ) {
return null;
}
final View decorView = activity.getWindow().getDecorView();
ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
int previousKeyboardHeight = -1;
Rect rect = new Rect();
boolean lastVisibleState = false;
@Override
public void onGlobalLayout() {
rect.setEmpty();
decorView.getWindowVisibleDisplayFrame( rect );
int displayHeight = rect.bottom - rect.top;
int height = decorView.getHeight() - rect.top;
int keyboardHeight = height - displayHeight;
if ( previousKeyboardHeight != keyboardHeight ) {
boolean hide = ( double ) displayHeight / height > 0.8;
if ( hide != lastVisibleState ) {
listener.onSoftKeyBoardChange( keyboardHeight, !hide );
lastVisibleState = hide;
}
}
previousKeyboardHeight = height;
}
};
decorView.getViewTreeObserver().addOnGlobalLayoutListener( onGlobalLayoutListener );
return onGlobalLayoutListener;
}
public static void removeSoftKeyboardObserver( Activity activity, ViewTreeObserver.OnGlobalLayoutListener listener ) {
if ( !isAliveActivity( activity ) || listener == null ) {
return;
}
final View decorView = activity.getWindow().getDecorView();
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN ) {
decorView.getViewTreeObserver().removeOnGlobalLayoutListener( listener );
} else {
decorView.getViewTreeObserver().removeGlobalOnLayoutListener( listener );
}
}
private static boolean isAliveActivity( Activity activity ) {
return activity != null
&& activity.getWindow() != null
&& activity.getWindow().getDecorView() != null
&& activity.getWindow().getDecorView().getViewTreeObserver() != null;
}
}

View File

@@ -0,0 +1,43 @@
package com.mogo.eagle.core.utilcode.util;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class ThreadPoolService {
private static final ExecutorService SERVICE = Executors.newFixedThreadPool( 3, new ThreadFactoryImpl() );
private static final ExecutorService SINGLE_THREAD_SERVICE = Executors.newSingleThreadExecutor(new SingleThreadFactoryImpl());
private static class ThreadFactoryImpl implements ThreadFactory {
private static int mCounter = 1;
@Override
public Thread newThread( Runnable r ) {
return new Thread( r, "ThreadPoolService - " + mCounter++ );
}
}
/**
* 单线程队列执行的ThreadFactory实现应该只会new一个Thread
*/
private static class SingleThreadFactoryImpl implements ThreadFactory{
private static int counter = 1;
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "SingleThread - " + counter++);
}
}
private ThreadPoolService() {
}
public static void execute( Runnable task ) {
SERVICE.execute( task );
}
public static void singleExecute(Runnable task) {
SINGLE_THREAD_SERVICE.execute(task);
}
}

View File

@@ -0,0 +1,41 @@
package com.mogo.eagle.core.utilcode.util;
import android.os.Handler;
import android.os.Looper;
public class UiThreadHandler {
private static final Handler sUiHandler = new Handler( Looper.getMainLooper() );
private static final Object sToken = new Object();
public UiThreadHandler() {
}
public static boolean post( Runnable r ) {
return sUiHandler != null && sUiHandler.post( r );
}
public static boolean postDelayed( Runnable r, long delayMillis ) {
return sUiHandler != null && sUiHandler.postDelayed( r, delayMillis );
}
public static Handler getsUiHandler() {
return sUiHandler;
}
public static boolean postOnceDelayed( Runnable r, long delayMillis ) {
if ( sUiHandler == null ) {
return false;
} else {
sUiHandler.removeCallbacks( r, sToken );
return sUiHandler.postDelayed( r, delayMillis );
}
}
public static void removeCallbacks( Runnable runnable ) {
if ( sUiHandler != null ) {
sUiHandler.removeCallbacks( runnable );
}
}
}

View File

@@ -1,15 +1,18 @@
package com.mogo.eagle.core.utilcode.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Locale;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
/**
* <pre>
@@ -116,4 +119,30 @@ public class ViewUtils {
(LayoutInflater) Utils.getApp().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflate.inflate(layoutId, null);
}
public static Bitmap fromView(View view) {
view.setDrawingCacheEnabled(true);
processChildView(view);
view.destroyDrawingCache();
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
// Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas( bitmap );
// view.draw( canvas );
// return bitmap;
Bitmap bitmap = null;
return (bitmap = view.getDrawingCache()) != null ? bitmap.copy(Bitmap.Config.ARGB_8888, false) : null;
}
public static void processChildView(View view) {
if (!(view instanceof ViewGroup)) {
if (view instanceof TextView) {
((TextView) view).setHorizontallyScrolling(false);
}
} else {
for (int var1 = 0; var1 < ((ViewGroup) view).getChildCount(); ++var1) {
processChildView(((ViewGroup) view).getChildAt(var1));
}
}
}
}

View File

@@ -0,0 +1,74 @@
package com.mogo.eagle.core.utilcode.util;
import android.content.Context;
public class WindowUtils {
public static int getStatusBarHeight( Context context ) {
if ( context == null ) {
return 0;
} else {
int result = 0;
int resourceId = context.getResources().getIdentifier( "status_bar_height", "dimen", "android" );
if ( resourceId > 0 ) {
result = context.getResources().getDimensionPixelSize( resourceId );
}
return result;
}
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px( Context context, float dpValue ) {
if ( context == null ) {
return 0;
}
final float scale = context.getResources().getDisplayMetrics().density;
return ( int ) ( dpValue * scale + 0.5f );
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip( Context context, float pxValue ) {
if ( context == null ) {
return 0;
}
final float scale = context.getResources().getDisplayMetrics().density;
return ( int ) ( pxValue / scale + 0.5f );
}
public static String getScreenPixels( Context context ) {
if ( context == null ) {
return "";
}
return getScreenWidth( context ) + "*" + getScreenHeight( context );
}
public static int getScreenWidth( Context context ) {
if ( context == null ) {
return 0;
}
return context.getResources().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight( Context context ) {
if ( context == null ) {
return 0;
}
return context.getResources().getDisplayMetrics().heightPixels;
}
public static int getScreenDpi( Context context ) {
if ( context == null ) {
return 0;
}
return context.getResources().getDisplayMetrics().densityDpi;
}
}