终止应用程序后,前台服务将终止

时间:2019-06-28 12:41:20

标签: android service

我一直在尝试让服务在后台运行,因为我已经实现了前台方法,但仍然杀死了应用程序。 即使该应用程序被终止,我也需要此服务才能向我返回用户的位置。

MainActivity.kt

private fun kickStartService(){
        var intent = Intent(this , LocationService::class.java)
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        intent.putExtra("extra" , "extra")
        ContextCompat.startForegroundService( this , intent)
//        startService( intent)

    }

LocationService.kt



override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        myNotification(intent)
        mGoogleApiClient = GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build()

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        if (!mGoogleApiClient!!.isConnected) {
            mGoogleApiClient!!.connect()
        }

        return START_NOT_STICKY
    }



    fun myNotification( intent : Intent?){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            var extra = intent?.getStringExtra("extra")
            var pendingIntent: PendingIntent =
                Intent(this, MainActivity::class.java).let { notificationIntent ->
                    PendingIntent.getActivity(this, 0, notificationIntent, 0)
                }
            var notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Notification Title")
                .setContentText(extra)
                .setSmallIcon(R.drawable.notification_icon_background)
                .setContentIntent(pendingIntent)
                .setTicker("Ticker Text")
                .build()
            startForeground(1, notification)
        }
    }

1 个答案:

答案 0 :(得分:0)

好吧,我不好,我使用的是Xiaomi Mi Mix 2,因此,如果您已从应用程序管理器中的应用程序设置自动启动,那么Mi不会让您启动前台服务。一旦打开它,我的前台服务就可以正常运行。