GlobaExt.kt 7.2 KB

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