微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用andoid kotlin在后台获取位置

如何解决如何使用andoid kotlin在后台获取位置

class LocationService : Service() {
    private var mLocationManager: LocationManager? = null
    private val binder = LocalBinder()
    var notification: Notification? = null


    var mLocationListeners = arrayOf(LocationListener(LocationManager.GPS_PROVIDER),LocationListener(LocationManager.NETWORK_PROVIDER))

    class LocationListener(provider: String) : android.location.LocationListener {
        internal var mLastLocation: Location

        init {
            Log.e(TAG,"LocationListener $provider")
            mLastLocation = Location(provider)
        }

        override fun onLocationChanged(location: Location) {
            Log.e(TAG,"onLocationChanged: $location")
            mLastLocation.set(location)
            Log.v("LastLocation",mLastLocation.latitude.toString() + "  " + mLastLocation.longitude.toString())
        }

        override fun onProviderdisabled(provider: String) {
            Log.e(TAG,"onProviderdisabled: $provider")
        }

        override fun onProviderEnabled(provider: String) {
            Log.e(TAG,"onProviderEnabled: $provider")
        }

        override fun onStatusChanged(provider: String,status: Int,extras: Bundle) {
            Log.e(TAG,"onStatusChanged: $provider")
        }
    }

    override fun onBind(arg0: Intent): IBinder? {
        return binder
    }

    override fun onStartCommand(intent: Intent?,flags: Int,startId: Int): Int {
        Log.e(TAG,"onStartCommand")
        super.onStartCommand(intent,flags,startId)
        return START_STICKY
    }

    override fun onCreate() {
        Log.e(TAG,"onCreate")
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val NOTIFICATION_CHANNEL_ID = "com.example.simpleapp"
            val channelName = "My Background Service"
            val chan = NotificationChannel(NOTIFICATION_CHANNEL_ID,channelName,notificationmanager.IMPORTANCE_NONE)
            chan.lightColor = Color.BLUE

            chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
            val manager: notificationmanager = (getSystemService(NOTIFICATION_SERVICE) as notificationmanager)!!
            manager.createNotificationChannel(chan)

            val notificationBuilder: Notification.Builder = Notification.Builder(this,NOTIFICATION_CHANNEL_ID)
            var notification: Notification = notificationBuilder.setongoing(true)
                    .setSmallIcon(R.drawable.ic_android)
                    .setContentTitle("App is running in background")
                    .setPriority(notificationmanager.IMPORTANCE_MIN)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .build()
            startForeground(2,notification)
        }


        initializeLocationManager()
        try {
            mLocationManager!!.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,LOCATION_INTERVAL.toLong(),LOCATION_disTANCE,mLocationListeners[1])
        } catch (ex: java.lang.SecurityException) {
            Log.i(TAG,"fail to request location update,ignore",ex)
        } catch (ex: IllegalArgumentException) {
            Log.d(TAG,"network provider does not exist," + ex.message)
        }

        try {
            mLocationManager!!.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,mLocationListeners[0])
        } catch (ex: java.lang.SecurityException) {
            Log.i(TAG,"gps provider does not exist " + ex.message)
        }

    }

    override fun onDestroy() {
        Log.e(TAG,"onDestroy")
        super.onDestroy()
        val broadcastIntent = Intent(this,SendRestartbroadCastReceiver::class.java)
        sendbroadcast(broadcastIntent)`enter code here`

    }

    private fun initializeLocationManager() {
        Log.e(TAG,"initializeLocationManager")
        if (mLocationManager == null) {
            mLocationManager = applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        }
    }

    companion object {
        private val TAG = "BOOMBOOMTESTGPS"
        private val LOCATION_INTERVAL = 1000
        private val LOCATION_disTANCE = 0f
    }

    inner class LocalBinder : Binder() {
        val service: LocationService
            get() = this@LocationService
    }
}

// 广播接收器

class SendRestartbroadCastReceiver: broadcastReceiver() {
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onReceive(p0: Context?,p1: Intent?) {
        GlobalScope.launch {
            p0?.startForegroundService(Intent(p0,LocationService::class.java))

        }
    }
}

MainActivity.kt

class MainActivity : FlutterActivity() {
    private val CHANNEL = "samples.Flutter.dev/battery"
    private var permission: Boolean = false




    var mService: LocationService? = null
    var mBound = false


    @RequiresApi(Build.VERSION_CODES.O)
    override fun configureFlutterEngine(@NonNull FlutterEngine: FlutterEngine) {
        super.configureFlutterEngine(FlutterEngine)
        MethodChannel(FlutterEngine.dartExecutor.binaryMessenger,CHANNEL).setMethodCallHandler { call,result ->
            if (call.method == "getbatterylevel") {
                fn_permission()
                if (permission) {
                    var forService = Intent(this@MainActivity,LocationService::class.java)


                    GlobalScope.launch {
                        var forService = Intent(this@MainActivity,LocationService::class.java)

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                            startForegroundService(forService);
//                            Intent(this,MyBoundService::class.java).also { intent ->
//                                bindService(intent,serviceConnection,Context.BIND_AUTO_CREATE)
//                            }
//                            bindService(forService,mConnection,Context.BIND_AUTO_CREATE)
//                            startService(forService)
                            startForegroundService(forService)

                        } else {
                            startService(forService);
//                            bindService(forService,Context.BIND_AUTO_CREATE)
                        }
//                        runOnUiThread{
//                            startForegroundService(forService)
//                        }


                    }
                }


            }
        }
    }


    companion object {
        const val CHANNEL_ID = "exampleServiceChannel"
        private const val REQUEST_PERMISSIONS = 100
    }

    private fun fn_permission() {
        if (ContextCompat.checkSelfPermission(applicationContext,Manifest.permission.ACCESS_FINE_LOCATION) !== PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(applicationContext,Manifest.permission.ACCESS_FINE_LOCATION) !== PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity,Manifest.permission.ACCESS_FINE_LOCATION) && ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity,Manifest.permission.ACCESS_BACKGROUND_LOCATION) && ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity,Manifest.permission.ACCESS_COARSE_LOCATION)) {
            } else {
                ActivityCompat.requestPermissions(this@MainActivity,arrayOf(Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_BACKGROUND_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION
                ),REQUEST_PERMISSIONS)
            }
        } else {
            permission = true
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int,permissions: Array<out String>,grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode,permissions,grantResults)
        when (requestCode) {
            REQUEST_PERMISSIONS -> {
                if (grantResults.isNotEmpty() && grantResults[0] === PackageManager.PERMISSION_GRANTED) {
                    permission = true
                } else {
                    Toast.makeText(applicationContext,"Please allow the permission",Toast.LENGTH_LONG).show()
                }
            }
        }
    }


    private val mConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName,service: IBinder) {
            // This is called when the connection with the service has been
            // established,giving us the service object we can use to
            // interact with the service.  Because we have bound to a explicit
            // service that we kNow is running in our own process,we can
            // cast its IBinder to a concrete class and directly access it.
            val binder = service as LocationService.LocalBinder

            mService = binder.service
            mBound = true




        }

        override fun onServicedisconnected(className: ComponentName) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is,its process crashed.
            // Because it is running in our same process,we should never
            // see this happen.
//            mLocationService = null
//            Toast.makeText(this@Binding,R.string.local_service_disconnected,//                    Toast.LENGTH_SHORT).show()
            mBound = false
        }
    }




}

  1. 我是一名 Flutter 开发人员,对 kotlin 知之甚少,我尝试了谷歌上所有可用的解决方案。很抱歉糟糕的编码风格。其实我现在很绝望。任何可以帮助我的人。我尝试了他在谷歌中可用的所有方法,但几分钟后当我的应用程序处于后台时。我停止发送数据。
  2. 我什至尝试过使用作业调度程序,但这也不起作用
  3. 我尝试在 android 中同时使用前台后台服务
  4. I Visit this page which is official android page they just update this page on March 11 2021 我尝试了不同的解决方案,但没有奏效
  5. 任何可以帮助我的机构

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。