LatLongService.kt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. package com.jld.vod.service
  2. import android.annotation.SuppressLint
  3. import android.app.Notification
  4. import android.app.NotificationManager
  5. import android.app.PendingIntent
  6. import android.app.Service
  7. import android.content.Context
  8. import android.content.Intent
  9. import android.graphics.Bitmap
  10. import android.graphics.BitmapFactory
  11. import android.os.Handler
  12. import android.os.IBinder
  13. import android.os.Message
  14. import android.view.WindowManager
  15. import android.widget.Toast
  16. import androidx.lifecycle.ViewModelProvider
  17. import androidx.lifecycle.observe
  18. import androidx.room.Room
  19. import com.google.android.gms.maps.model.LatLng
  20. import com.google.gson.Gson
  21. import com.google.gson.reflect.TypeToken
  22. import com.jld.vod.R
  23. import com.jld.vod.config.Config
  24. import com.jld.vod.db.CarSiteAllDatabase
  25. import com.jld.vod.model.bean.*
  26. import com.jld.vod.model.event.MapsEvent
  27. import com.jld.vod.model.event.SiteEvent
  28. import com.jld.vod.utils.LatLongUtils
  29. import com.jld.vod.utils.LogUtils
  30. import com.jld.vod.utils.http.OkHttpUtils
  31. import com.jld.vod.utils.SharedPrefUtils
  32. import com.jld.vod.view.widget.CustomGEOAdDialog
  33. import com.jld.vod.viewmodel.MainViewModel
  34. import okhttp3.Call
  35. import okhttp3.Response
  36. import org.greenrobot.eventbus.EventBus
  37. import java.io.IOException
  38. import java.io.InputStream
  39. import java.net.HttpURLConnection
  40. import java.net.URL
  41. /**
  42. * @author ZhaoFuXin
  43. * @Email:18276061387@163.com
  44. * @description:
  45. * @date :2020/9/18 14:03
  46. */
  47. class LatLongService :Service() {
  48. private var gson:Gson?= null
  49. private var carsitealldb:CarSiteAllDatabase? =null
  50. private var siteId:Long?= 0
  51. private var sitearr = arrayOfNulls<Long>(2)
  52. private var indexsite:Int = 0
  53. private var carinfo:CarSiteAllBean?=null
  54. private lateinit var mCustom : CustomGEOAdDialog
  55. private var mContext: Context ?= null
  56. private val mHandler: Handler = @SuppressLint("HandlerLeak")
  57. object : Handler() {
  58. override fun handleMessage(msg: Message) {
  59. super.handleMessage(msg)
  60. when (msg.what) {
  61. 1->{
  62. val result: String = msg.obj.toString()
  63. // 把定位信息广播发送出去
  64. EventBus.getDefault().post(MapsEvent(result))
  65. try {
  66. val latlng = gson!!.fromJson(result, LatLongBean::class.java)
  67. var min :Double = 1000.0
  68. Thread(Runnable {
  69. var mCarSiteAll: List<CarSiteAllBean> = carsitealldb!!.carSiteAllDao().getAll()
  70. //查询数据库的站点信息,根据当前定位报站
  71. if (latlng!=null && mCarSiteAll.isNotEmpty() && latlng.flag) {
  72. LogUtils.logD("进入报站:$latlng")
  73. //获取本地经纬度
  74. val Latitude = latlng.data.Latitude
  75. val Longitude = latlng.data.Longitude
  76. val location = LatLng(Latitude, Longitude)
  77. //判断不超出经纬度范围
  78. if (Longitude <= 180 && Longitude >= -180 && Latitude <= 90 && Latitude >= -90) {
  79. for ((index, data) in mCarSiteAll.withIndex()) {
  80. //LogUtils.logD("距离=test"+data.name)
  81. //站台的位置
  82. val lat: Double = data.latitude.toDouble()
  83. val lng: Double = data.longitude.toDouble()
  84. val plalocation = LatLng(lat, lng)//定位值
  85. //根据经纬度测算距离(米)
  86. val Distance: Double = LatLongUtils.getDistance(location, plalocation)
  87. //LogUtils.logD("距离all="+data.name+Distance)
  88. //设置距离站点,然后报站
  89. if (Distance <= 1000) {
  90. //LogUtils.logD("距离<1000="+Distance)
  91. //判断最短距离报站
  92. if(min > Distance) {
  93. min = Distance
  94. indexsite = index
  95. carinfo = data
  96. }
  97. }
  98. }
  99. //LogUtils.logD("距离min="+min+"indexsite$indexsite"+"carinfo$carinfo")
  100. // 把到站的站点广播发送出去
  101. EventBus.getDefault().post(SiteEvent(indexsite+1))
  102. SharedPrefUtils.putInt(applicationContext,"SiteEvent",indexsite+1)//把到站点缓存
  103. //通过id报站判断是否相同重复报站
  104. if(carinfo!=null){
  105. val siteIds = carinfo!!.siteId //记录当前站点id
  106. // LogUtils.logD("siteIds="+siteIds+"====siteId"+data.siteId)
  107. if (siteIds != siteId) {//判断不是同一个站点
  108. //报站通知
  109. // addNotification(carinfo!!.name,carinfo!!.sInfo)
  110. //预加载通知
  111. // returnBitMap(carinfo!!.sImg,carinfo!!.name,carinfo!!.sInfo)
  112. siteId = siteIds
  113. initAdVert(siteId)
  114. // //取消报站
  115. // Thread.sleep(15000)
  116. // cleanNotification()
  117. }
  118. }
  119. }
  120. }else{
  121. LogUtils.logD("没有报站信息")
  122. }
  123. }).start()
  124. }catch (e:Exception) {
  125. e.printStackTrace()
  126. }
  127. }
  128. 2->{
  129. //开启通知
  130. val result = msg.obj as GEOAdvertBean
  131. LogUtils.logD("result"+result)
  132. if (result.data != null)
  133. {
  134. mCustom = CustomGEOAdDialog(mContext)
  135. mCustom.getWindow()!!.setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
  136. mCustom.setDataList(result.data)
  137. mCustom.show()
  138. }
  139. // addNotification(result.pat,result.info,result.bitmap)
  140. }
  141. }
  142. }
  143. }
  144. override fun onBind(intent: Intent?): IBinder? {
  145. return null
  146. }
  147. override fun onCreate() {
  148. super.onCreate()
  149. mContext = this
  150. //初始化db
  151. carsitealldb = Room.databaseBuilder(this, CarSiteAllDatabase::class.java, "carsiteall").build()
  152. //初始化gson
  153. gson = Gson()
  154. }
  155. override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
  156. //获取经纬度
  157. requestLocalLatLng()
  158. return super.onStartCommand(intent, flags, startId)
  159. }
  160. /**
  161. * 初始化广告模块
  162. */
  163. private fun initAdVert(sid : Long?) {
  164. LogUtils.logD("sid"+sid)
  165. OkHttpUtils.getInstance().getDataAsyn(Config.ApiBaseUrl+"/advert/findGEOAdvert?sid="+sid,object :OkHttpUtils.MyNetCall{
  166. override fun failed(call: Call?, e: IOException?) {
  167. LogUtils.logE(e.toString())
  168. }
  169. override fun success(call: Call?, response: Response?) {
  170. val json = response!!.body!!.string()
  171. LogUtils.logD("initGEOAdVert"+json)
  172. val mGEOAdvertBean= gson!!.fromJson(json, GEOAdvertBean::class.java)
  173. val msg = Message()
  174. msg.what = 2
  175. msg.obj = mGEOAdvertBean
  176. mHandler.sendMessage(msg)
  177. }
  178. })
  179. }
  180. /**
  181. * 心跳回调
  182. */
  183. private fun requestLocalLatLng() {
  184. mHandler.postDelayed(Runnable {
  185. requestLatLng()
  186. //getDebugStatus(AppUtil.getDeviceSN())
  187. //重新调用
  188. requestLocalLatLng()
  189. }, 3000)
  190. }
  191. /**
  192. * 获取经纬度
  193. */
  194. private fun requestLatLng() {
  195. Thread(Runnable {
  196. try {
  197. val response: Response = OkHttpUtils.getInstance()
  198. .getData(Config.ApiBaseUrl + "/synchronization/findGPS")
  199. val res = response.body!!.string()
  200. val msg = Message()
  201. msg.what = 1
  202. msg.obj = res
  203. mHandler.sendMessage(msg)
  204. } catch (e: Exception) {
  205. e.printStackTrace()
  206. }
  207. }).start()
  208. }
  209. /**
  210. * 弹出到站通知
  211. * @param pat
  212. */
  213. private fun addNotification(pat: String,info: String,bitmap: Bitmap) {
  214. val intent = Intent(this, LatLongService::class.java) //点击了之后进入的一个Actity
  215. val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
  216. val noti =
  217. Notification.Builder(this) // .setTicker("你懂的!")
  218. .setContentTitle(pat)
  219. .setContentText(info)
  220. // .setLargeIcon(
  221. // BitmapFactory.decodeResource(
  222. // resources, R.mipmap.maps_dialog))
  223. .setLargeIcon(bitmap)//设置图片
  224. // .setSmallIcon(Icon.createWithContentUri(Config.ApiBaseUrl+"/synchronization/previewImg?imgUrl=$imgUrl"))
  225. .setSmallIcon(R.mipmap.maps_dialog) //设置图标
  226. .setDefaults(Notification.DEFAULT_SOUND) //设置声音
  227. .setContentIntent(pendingIntent) //点击之后的页面
  228. .setFullScreenIntent(pendingIntent, true)
  229. .build()
  230. val manager =
  231. this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
  232. manager.notify(666, noti)
  233. }
  234. /**
  235. * 取消到站通知
  236. */
  237. private fun cleanNotification() {
  238. val manager =
  239. getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
  240. manager.cancel(R.mipmap.ic_launcher)
  241. manager.cancel(666)
  242. }
  243. /**
  244. * 加载动态图片
  245. */
  246. fun returnBitMap(url: String?,pat: String,info: String) {
  247. Thread(Runnable {
  248. try {
  249. LogUtils.logD("imageurl:$url")
  250. var imageUrl =URL(Config.ApiBaseUrl+"/synchronization/previewImg?imgUrl=$url")
  251. LogUtils.logD("imageurl:$imageUrl")
  252. val conn: HttpURLConnection = imageUrl.openConnection() as HttpURLConnection
  253. conn.doInput = true
  254. conn.connect()
  255. val inputStream: InputStream = conn.inputStream
  256. val bitmap = BitmapFactory.decodeStream(inputStream)
  257. inputStream.close()
  258. var notificationInfoBean=NotificationInfoBean(pat,info,bitmap)
  259. val msg = Message()
  260. msg.what = 2
  261. msg.obj = notificationInfoBean
  262. mHandler.sendMessage(msg)
  263. } catch (e: IOException) {
  264. e.printStackTrace()
  265. }
  266. }).start()
  267. }
  268. }