GlobaExt.kt 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. package com.develop.base.ext
  2. import android.Manifest
  3. import android.app.Application
  4. import android.content.Context
  5. import android.content.pm.PackageManager
  6. import android.content.res.Resources
  7. import android.graphics.Bitmap
  8. import android.graphics.BitmapFactory
  9. import android.graphics.drawable.Drawable
  10. import android.net.wifi.WifiInfo
  11. import android.net.wifi.WifiManager
  12. import android.os.Build
  13. import android.text.TextUtils
  14. import android.util.Patterns
  15. import android.widget.ImageView
  16. import androidx.annotation.DimenRes
  17. import androidx.core.app.ActivityCompat
  18. import androidx.core.content.ContextCompat
  19. import com.bumptech.glide.Glide
  20. import com.bumptech.glide.load.engine.DiskCacheStrategy
  21. import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
  22. import com.develop.base.app.BaseApp
  23. import com.develop.base.util.MMkvUtils
  24. import kotlinx.serialization.decodeFromString
  25. import kotlinx.serialization.encodeToString
  26. import kotlinx.serialization.json.Json
  27. import okhttp3.MediaType.Companion.toMediaTypeOrNull
  28. import okhttp3.MultipartBody
  29. import okhttp3.RequestBody
  30. import okhttp3.RequestBody.Companion.toRequestBody
  31. import java.io.File
  32. import java.io.IOException
  33. import java.io.InputStream
  34. import java.net.URI
  35. import java.text.SimpleDateFormat
  36. import java.util.*
  37. import java.util.regex.Pattern
  38. fun globalApp(): Application = BaseApp.application
  39. fun globalRes(): Resources = globalApp().resources
  40. // ------------------------------Any扩展-------------------------------------
  41. fun Any.toJson(): String = Json.encodeToString(this)
  42. fun Any.dimenRes(@DimenRes res: Int): Int {
  43. return globalApp().resources.getDimensionPixelSize(res)
  44. }
  45. // ------------------------------String扩展-------------------------------------
  46. fun String.fromJson(): Any = Json.decodeFromString(this)
  47. fun String.getHost(): String {
  48. var hostUrl = this
  49. if (!(hostUrl.startsWith("http://") || hostUrl.startsWith("https://"))) {
  50. hostUrl = "http://$this"
  51. }
  52. var returnVal = ""
  53. try {
  54. val uri = URI(hostUrl)
  55. returnVal = uri.host
  56. } catch (e: Exception) {
  57. }
  58. if (returnVal.endsWith(".html") || returnVal.endsWith(".htm")) {
  59. returnVal = ""
  60. }
  61. return "http://$returnVal"
  62. }
  63. fun String.isHttpUrl(): Boolean = Patterns.WEB_URL.matcher(this).matches()
  64. fun String.assetsUri2Bitmap(): Bitmap? {
  65. val path = this
  66. var image: Bitmap? = null
  67. val am = globalApp().resources.assets
  68. try {
  69. val stream: InputStream = am.open(path)
  70. image = BitmapFactory.decodeStream(stream)
  71. stream.close()
  72. } catch (e: IOException) {
  73. e.printStackTrace()
  74. }
  75. return image
  76. }
  77. fun String.jsonSpiltField(fieldName: String): String {
  78. if (fieldName.isEmpty()) {
  79. return ""
  80. }
  81. val regex = "(?<=(\"$fieldName\":\")).*?(?=(\"))"
  82. val pattern = Pattern.compile(regex)
  83. val matcher = pattern.matcher(this)
  84. while (matcher.find()) {
  85. if (!TextUtils.isEmpty(matcher.group().trim { it <= ' ' })) {
  86. return matcher.group().trim { it <= ' ' }
  87. }
  88. }
  89. return ""
  90. }
  91. fun String.createFolder() {
  92. val file = File(this)
  93. if (!file.exists()) {
  94. file.mkdirs()
  95. }
  96. }
  97. fun String.deleteFile(): Boolean {
  98. val file = File(this)
  99. if (!file.exists()) {
  100. return false
  101. }
  102. return file.delete()
  103. }
  104. fun timeStamp2Time(timeSeconds: Long, format: String = "yyyy/MM/dd HH:mm"): String? {
  105. val date = Date(timeSeconds * 1000)
  106. return SimpleDateFormat(format, Locale.getDefault()).format(date)
  107. }
  108. fun String.toCacheFolder(): String = globalApp().externalCacheDir.toString() + "/" + this
  109. // ------------------------------Int扩展-------------------------------------
  110. fun Int.resId2Drawable(): Drawable? = ContextCompat.getDrawable(globalApp(), this)
  111. fun Int.resId2Dimension(): Float = BaseApp.application.resources.getDimension(this)
  112. // ------------------------------RequestBody扩展-------------------------------------
  113. fun Map<String, String>.genMultipartBody(): RequestBody {
  114. val builder = MultipartBody.Builder()
  115. builder.setType(MultipartBody.FORM)//表单类型
  116. this.forEach {
  117. builder.addFormDataPart(it.key, it.value)
  118. }
  119. return builder.build()
  120. }
  121. fun Map<String, String>.genRequestBody(): Map<String, RequestBody> {
  122. val requestBodyMap: MutableMap<String, RequestBody> = HashMap()
  123. for (key in this.keys) {
  124. val requestBody: RequestBody =
  125. (if (this[key] == null) "" else this[key] ?: ""
  126. ).toRequestBody("text/plain".toMediaTypeOrNull())
  127. requestBodyMap[key] = requestBody
  128. }
  129. return requestBodyMap
  130. }
  131. fun GlobalApp(): Application {
  132. return BaseApp.application
  133. }
  134. fun getWifiMacAddress(context: Context): String {
  135. // 检查是否具有读取Wi-Fi状态的权限
  136. if (ActivityCompat.checkSelfPermission(
  137. context,
  138. Manifest.permission.ACCESS_WIFI_STATE
  139. ) != PackageManager.PERMISSION_GRANTED
  140. ) {
  141. // 无权限,请求权限
  142. // 这里需要您自行实现权限请求的逻辑
  143. return ""
  144. }
  145. val wifiManager =
  146. context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
  147. val wifiInfo: WifiInfo? = wifiManager.connectionInfo
  148. return if (wifiInfo != null) wifiInfo.macAddress else ""
  149. }
  150. /**
  151. * 获取SN
  152. * @return
  153. */
  154. fun getBrandNum(): String {
  155. return getSN().substring(0, 3)
  156. }
  157. /**
  158. * 获取SN
  159. * @return
  160. */
  161. fun getSN(): String {
  162. var serial: String
  163. // return "045A10220020123010120023"
  164. // return "000A30150020123010190001"
  165. return "002A30150020123010190001"
  166. // return "000A10390020123010190001"
  167. // return "010D30150020123010190001"
  168. // return "011A30150020123010190001"
  169. // return "007D20020020123010190001"
  170. // return "036I21060020123010180001"
  171. // return "030A10390020123010190001"
  172. // return "017A20060020123010190001"
  173. //通过反射获取sn号
  174. try {
  175. val c = Class.forName("android.os.SystemProperties")
  176. val get = c.getMethod("get", String::class.java)
  177. serial = get.invoke(c, "ro.serialno") as String
  178. if (serial != "" && serial != "unknown") return serial
  179. //9.0及以上无法获取到sn,此方法为补充,能够获取到多数高版本手机 sn
  180. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) serial = Build.getSerial()
  181. } catch (e: java.lang.Exception) {
  182. serial = "unknown"
  183. }
  184. return serial
  185. }
  186. fun ImageView.load(data: Any?) {
  187. Glide.with(this.context).load(data)
  188. .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
  189. .into(this)
  190. }
  191. fun ImageView.load(data: Any?, width: Int, height: Int) {
  192. Glide.with(this.context)
  193. .asDrawable()
  194. .load(data)
  195. .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
  196. .skipMemoryCache(false)
  197. .override(width, height)
  198. .dontAnimate()
  199. .into(this)
  200. }
  201. fun ImageView.load(data: Any?, error: Int) {
  202. Glide.with(this.context).load(data)
  203. .error(error)
  204. .transition(DrawableTransitionOptions.withCrossFade())
  205. .into(this)
  206. }
  207. fun isNightTheme(): Boolean {
  208. return MMkvUtils.getBool("nightTheme", false)
  209. }
  210. fun isFrLanguage(): Boolean {
  211. return MMkvUtils.getString("CURRENT_LANGUAGE") == "FR"
  212. }
  213. fun setNightTheme(isNight: Boolean) {
  214. MMkvUtils.save("nightTheme", isNight)
  215. }
  216. fun setIsBrand036I(is036I: Boolean) {
  217. MMkvUtils.save("is036I", is036I)
  218. }
  219. fun isBrand036I(): Boolean {
  220. return MMkvUtils.getBool("is036I", false)
  221. }
  222. fun setIsBrand011A(is011A: Boolean) {
  223. MMkvUtils.save("is011A", is011A)
  224. }
  225. fun isBrand011A(): Boolean {
  226. return MMkvUtils.getBool("is011A", false)
  227. }