Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android開発】アクティビティが通知から呼び出されたかどうかを判定する方法

このチュートリアルでは、Androidアプリにおいてアクティビティが通知(Notification)から呼び出されたかどうかを判定する方法を解説します。通知タップ時の挙動を出し分けたい場合などに役立つテクニックです。

仕組みのポイント

判定には PendingIntent に設定した IntentputExtra() でフラグを持たせるのが基本です。通知から起動された場合はExtraに値が入っているため、onCreate() 内でその値を読み取ることで、起動元が通知なのかどうかを判別できます。

手順1:プロジェクトの作成

まずはAndroid Studioを開き、「File」→「New Project」を選択して、必要な項目をすべて入力し、新しいプロジェクトを作成してください。

手順2:レイアウトファイル(res/layout/activity_main.xml)の編集

次に、以下のコードを res/layout/activity_main.xml に追加します。画面中央に「Create Notification」というボタンを配置するシンプルなレイアウトです。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnCreateNotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_centerInParent="true"
        android:text="Create Notification" />

</RelativeLayout>

手順3:MainActivityへのコード追加

続いて、src/MainActivity に以下のコードを記述します。ボタン押下時に通知を生成し、その PendingIntent"fromNotification" というキーでboolean値を渡している点に注目してください。アクティビティ側では getIntent().getExtras() を確認することで、通知経由での起動かどうかをログに出力できます。

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // IntentにExtraが設定されているかチェック
        if (getIntent().getExtras() != null) {
            Bundle b = getIntent().getExtras();
            boolean cameFromNotification = b.getBoolean("fromNotification");
            Log.i("Came from notification", String.valueOf(cameFromNotification));
        }
    }

    public void createNotification(View view) {
        // 通知から起動する際のIntentにフラグを設定
        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
        notificationIntent.putExtra("fromNotification", true);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
        mBuilder.setContentTitle("My Notification");
        mBuilder.setContentIntent(pendingIntent);
        mBuilder.setContentText("Notification Listener Service Example");
        mBuilder.setTicker("Notification Listener Service Example");
        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);

        // Android 8.0(API 26)以降は通知チャンネルが必要
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }
        assert mNotificationManager != null;
        mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
    }
}

補足:Android 8.0(Oreo)以降では通知チャンネルの作成が必須となっているため、上記コードのように Build.VERSION.SDK_INT によるバージョン分岐を行っています。また、通知タップ後に古いインスタンスが残らないよう、FLAG_ACTIVITY_CLEAR_TOPFLAG_ACTIVITY_SINGLE_TOP を組み合わせています。

手順4:AndroidManifest.xml の編集

最後に、AndroidManifest.xml に以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.notifyme">

    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

アプリの実行と動作確認

それでは、実際にアプリを実行してみましょう。実機のAndroidスマートフォンをPCに接続していることを前提としています。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。デバイス選択ダイアログでお使いのモバイル端末を選択すると、端末にアプリの初期画面が表示されます。

画面中央の「Create Notification」ボタンをタップすると通知が表示され、その通知をタップして再度アプリを開くと、Logcatに「Came from notification: true」と出力されます。逆に通常のランチャーから起動した場合には、Extraが存在しないためログが出力されません。

【Android開発】アクティビティが通知から呼び出されたかどうかを判定する方法

【Android開発】アクティビティが通知から呼び出されたかどうかを判定する方法

まとめ

このように、通知からアクティビティを起動する際に Intent のExtraへ識別用のフラグを仕込んでおくことで、起動元が通知かどうかを簡単に判定できます。通知ごとに異なる画面遷移や処理を実装したい場合にも応用できる、実用的なパターンですので、ぜひ活用してみてください。

  1. Androidでリマインダー通知を実装する方法を初心者向けに解説

    この記事では、Androidアプリで毎日決まった時刻に通知を表示する「リマインダー通知」の実装方法を、サンプルコードとともにステップごとに解説します。AlarmManagerとServiceを組み合わせることで、アプリが起動していなくても指定時刻に通知を届けられる仕組みを作れます。全体の仕組み本サンプルでは、以下の流れでリマインダー通知を実現します。1. 画面上のボタンをタップすると、翌日の午前0時に通知を発行するようAlarmManagerに登録します。2. 指定時刻になるとシステムがNotifyService(Serviceクラス)を起動します。3. Service内でNotificati

  2. 【Android】アクティビティを再起動する方法をサンプルコード付きで解説

    はじめに このチュートリアルでは、Androidアプリでアクティビティ(Activity)を再起動する方法を解説します。アクティビティの再起動は、finish()で現在のアクティビティを終了し、startActivity()で同じインテントを使って再度起動するという手法で実現できます。 ここでは、ボタンをタップするとランダムな数値が表示し直されるサンプルアプリを作成しながら、具体的な手順を紹介します。 ステップ1:新規プロジェクトの作成 Android Studioを開き、「File」→「New Project」を選択して、必要な情報をすべて入力し、新しいプロジェクトを作成します。 ステッ