【Android】通知タップ時にアプリ起動中or未起動を判定する


前提

Android Studio 4.1.2
Kotlin 1.3.72
minSdkVersion 28
targetSdkVersion 29

元々は仕事で通知をタップした時にアプリ起動中or未起動を判定して、起動中ならアプリをユーザーに表示する(フォアグラウンドにする)ということがしたくて調べてました。今回はアプリ起動中or未起動の判定までを書き、別の記事でアプリをユーザーに表示する(フォアグラウンドにする)ところを書きます。 kwn1125.hatenablog.com

目標

通知タップ時にアプリ起動中or未起動を判定する。

実装

通知をタップした時に処理を実行したいのでServiceクラスを作ります。

アプリ起動中or未起動を判定するために、アプリ内のタスクの数を使います。ActivityManagerクラスを使ってアプリ内のタスクの一覧をリストで取得し、空ならアプリ未起動、そうでなければアプリ起動中になります。

package com.example.testapplication

import android.app.ActivityManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.util.Log

class MyService : Service() {
    companion object {
        private const val TAG = "MyService"
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val appTasks = activityManager.appTasks

        if (appTasks.isEmpty()) {
            Log.d(TAG, "未起動")
        } else {
            Log.d(TAG, "起動中")
        }

        stopSelf()
        return START_NOT_STICKY
    }

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


MainActivityクラスのonCreateメソッド内に、通知を発行しその通知をタップしたらMyServiceを実行するようにコードを書きます(onCreateメソッド内に全処理書いてるのはすぐ試したいからなので許してほしい)。
これでアプリ起動時に通知が表示され、通知をタップした時にアプリ起動中ならログに「起動中」、アプリ未起動ならログに「未起動」と出力されます。

package com.example.testapplication

import android.app.PendingIntent
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val channel = NotificationChannel(
                "channel_1",
                "Channel1",
                NotificationManager.IMPORTANCE_HIGH)
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)

        val pendingIntent = PendingIntent.getService(
                this, 
                0,
                Intent(this, MyService::class.java),
                PendingIntent.FLAG_ONE_SHOT)

        val notification = NotificationCompat.Builder(this, "channel_1")
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("title")
                .setContentText("body")
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .build()
        NotificationManagerCompat.from(this).notify(0, notification)
    }
}