Androidでプッシュ通知を受信した後にアクティビティを開く方法
本記事では、AndroidアプリでFirebase Cloud Messaging(FCM)を使用してプッシュ通知を受信し、その通知をタップしたときに特定のアクティビティを開く方法を解説します。
ポイントは、通知にPendingIntentを設定することです。これにより、ユーザーが通知をタップした際に、任意のアクティビティを起動できるようになります。さらに、Intentにデータ(Extras)を渡せば、起動先のアクティビティ側でその内容を受け取ることも可能です。
手順1:Android Studioで新規プロジェクトを作成する
Android Studioを起動し、「File」⇒「New Project」を選択して、必要な情報を入力して新しいプロジェクトを作成します。あわせて、Firebaseコンソールでプロジェクトを作成し、google-services.jsonをアプリに追加しておいてください。
手順2:MyFirebaseMessagingService.javaにコードを追加する
Firebaseからメッセージを受信するためのサービスクラスに、以下のコードを実装します。
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
@Override
public void onNewToken(String s) {
super.onNewToken(s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// 通知タップ時に開きたいアクティビティを指定したIntentを作成
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.putExtra("NotificationMessage", "I am from Notification");
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// PendingIntentを生成し、通知に紐付ける
PendingIntent resultIntent = PendingIntent.getActivity(
getApplicationContext(), 0, notificationIntent, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext(),
default_notification_channel_id)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Test")
.setContentText("Hello! This is my first push notification")
.setContentIntent(resultIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 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());
}
}コードのポイント解説
- Intentの生成:
notificationIntentには、通知タップ時に開きたいアクティビティ(ここではMainActivity)を指定します。putExtra()を使うことで、文字列などのデータを起動先に渡すこともできます。 - フラグの設定:
FLAG_ACTIVITY_CLEAR_TOPとFLAG_ACTIVITY_SINGLE_TOPを組み合わせることで、既にアクティビティが起動している場合に重複して新しいインスタンスを作成せず、既存のインスタンスを再利用します。 - PendingIntent: 通知はアプリのプロセス外(システム)から発行されるため、通常のIntentではなくPendingIntentとして渡す必要があります。
- 通知チャンネル: Android 8.0以降では、通知を表示するために通知チャンネルの作成が必須です。チャンネルIDと重要度(IMPORTANCE_HIGHなど)を指定して作成します。
補足:マニフェストへの登録を忘れずに
作成したサービスクラスは、AndroidManifest.xml内に以下のように宣言する必要があります。
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>また、build.gradleにFirebase Messagingの依存関係を追加することも忘れないでください。
implementation 'com.google.firebase:firebase-messaging:21.1.0'
以上で実装は完了です。アプリをビルドして実行し、Firebaseコンソールまたはサーバー側からメッセージを送信すると、プッシュ通知が表示され、それをタップすると指定したアクティビティが起動します。起動先のアクティビティでは、getIntent().getStringExtra("NotificationMessage")のようにして、通知から渡されたデータを取得できます。
-
【Android】アクティビティを再起動する方法をサンプルコード付きで解説
はじめに このチュートリアルでは、Androidアプリでアクティビティ(Activity)を再起動する方法を解説します。アクティビティの再起動は、finish()で現在のアクティビティを終了し、startActivity()で同じインテントを使って再度起動するという手法で実現できます。 ここでは、ボタンをタップするとランダムな数値が表示し直されるサンプルアプリを作成しながら、具体的な手順を紹介します。 ステップ1:新規プロジェクトの作成 Android Studioを開き、「File」→「New Project」を選択して、必要な情報をすべて入力し、新しいプロジェクトを作成します。 ステッ
-
【Android】アクティビティでソフトキーボードの開閉リスナーを実装する方法
この記事では、Androidアプリのアクティビティ内でソフトキーボード(SoftKeyboard)の表示・非表示を検知するリスナーを実装する方法を、サンプルコードとともにわかりやすく解説します。ソフトキーボードの開閉を検知するには、ViewTreeObserver.OnGlobalLayoutListener を利用して、画面の可視領域の変化を監視するのが一般的な手法です。手順1:新規プロジェクトの作成Android Studioを起動し、メニューから「File」→「New Project」を選択して、必要な項目を入力して新しいプロジェクトを作成します。手順2:レイアウトファイル(res/la