Содержимое службы Foreground не возобновляет приложение, а перезапускает его - PullRequest
0 голосов
/ 08 января 2020

Я просматривал много тем о возобновлении активности из службы переднего плана, не найдя никакого конкретного ответа на мою проблему.

Я пытаюсь добавить службу переднего плана в свое приложение и хочу, чтобы Приложение должно быть возобновлено при нажатии на сервисное уведомление вместо его перезапуска. Я попытался использовать метод getLaunchIntentForPackage() из PackageManager, который наиболее близок к тому, что я хочу сделать.

Тем не менее, onCreate действия все еще вызывается при возобновлении приложения, нажимая на уведомление.

Итак, вот мой вопрос, как возобновить работу приложения из намерения содержимого уведомления?

Я запускаю свой ForegroundService в onStop действия, поэтому он вызывается, когда приложение убито или отправлено в фоновый режим.

override fun onStop() {
    super.onStop()
    Log.v(TAG, "onStop")
    ForegroundService.startService(this, "Hellooooooo, here is the background")
}

ForegroundService

class ForegroundService: Service() {

    companion object {
        private const val CHANNEL_ID = "ForegroundServiceChannel"

        fun startService(context: Context, message: String) {
            val startIntent = Intent(context, ForegroundService::class.java)
            startIntent.putExtra("inputExtra", message)
            ContextCompat.startForegroundService(context, startIntent)
        }
        fun stopService(context: Context) {
            val stopIntent = Intent(context, ForegroundService::class.java)
            context.stopService(stopIntent)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val input = intent!!.getStringExtra("inputExtra")

        val launchIntent = packageManager.getLaunchIntentForPackage(APP_PACKAGE)
        val contentIntent = PendingIntent.getActivity(applicationContext, 0,
            launchIntent, 0)

        val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Foreground Service")
            .setContentText(input)
            .setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.ic_call_to_action)
            .setOngoing(true)
            .build()

        startForeground(1, notification)
        createNotificationChannel()

        return START_NOT_STICKY
    }

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(
                CHANNEL_ID,
                "Foreground Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            val manager = getSystemService(
                NotificationManager::class.java
            )
            manager?.createNotificationChannel(serviceChannel)
        }

    }

}
...