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

Androidで通知タップ時にパラメータをアクティビティへ渡す方法を解説

本記事では、Androidで通知(Notification)をタップした際に、通知に埋め込んだパラメータ(データ)をアクティビティへ受け渡す方法を、サンプルコードとともに詳しく解説します。通知からアプリを開くときにメッセージや識別情報を渡したいケースで役立つ、実践的なテクニックです。

ステップ1:新規プロジェクトを作成する

Android Studioを起動し、メニューから「File → New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。

ステップ2:res/layout/activity_main.xml にコードを追加する

以下のコードをレイアウトファイルに追加してください。このレイアウトには、通知から受け取ったメッセージを表示する TextView と、通知を生成する Button が配置されています。

<?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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvNotify"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnNotify"
        android:layout_margin="16dp" />

    <Button
        android:id="@+id/btnNotify"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:onClick="createNotification"
        android:text="create notification" />
</RelativeLayout>

ステップ3:src/MainActivity.java にコードを追加する

次に、メインアクティビティに以下のコードを記述します。ここが本記事の核心部分で、通知タップ時のパラメータ受け渡しを実現しています。

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.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

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);
        onNewIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle extras = intent.getExtras();
        if (extras != null) {
            if (extras.containsKey("NotificationMessage")) {
                String msg = extras.getString("NotificationMessage");
                TextView tvNotify = findViewById(R.id.tvNotify);
                tvNotify.setText(msg);
            }
        }
    }

    public void createNotification(View view) {
        Intent notificationIntent = new Intent(MainActivity.this, 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 resultIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent, 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, 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);

        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());
    }
}

コードのポイント解説

  • putExtra() によるデータ埋め込み: 通知タップ時に起動される Intent に対して putExtra() を使い、「NotificationMessage」というキーで文字列を格納しています。
  • フラグ設定: FLAG_ACTIVITY_CLEAR_TOP と FLAG_ACTIVITY_SINGLE_TOP を指定することで、すでに存在する MainActivity のインスタンスが再利用され、onCreate() ではなく onNewIntent() が呼び出されます。
  • onNewIntent() での受信処理: インテントの Extras から「NotificationMessage」キーの値を取り出し、TextView に表示しています。onCreate() 内でも getIntent() を使って同様のチェックを行っているため、アプリが未起動の場合でも正しく動作します。
  • PendingIntent: 通知がタップされたタイミングでシステムが発行できるよう、Intent を PendingIntent.getActivity() でラップし、setContentIntent() にセットしています。
  • 通知チャンネル: Android 8.0(APIレベル26 / Oreo)以降では通知チャンネルの作成が必須のため、Build.VERSION.SDK_INT でOSバージョンを判定してチャンネルを生成しています。

ステップ4:AndroidManifest.xml にコードを追加する

マニフェストファイルを以下のように編集します。MainActivity がランチャーアクティビティとして登録されていることを確認してください。

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

    <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」アイコンをクリックしてください。デバイス選択画面で自分のモバイル端末を選択すると、端末にアプリのデフォルト画面が表示されます。

ボタンをタップして通知を表示させた後、その通知をタップしてみてください。「I am from Notification」というメッセージが画面上の TextView に表示されれば、通知からアクティビティへのパラメータ受け渡しが成功です。

  1. 【Android】1つのフラグメントから別のフラグメントへデータを送信する方法(インターフェース活用の実装例)

    はじめに このチュートリアルでは、Androidアプリで1つのフラグメント(Fragment)から別のフラグメントへデータを送信する方法を解説します。フラグメント同士は直接通信することができません。そこで本記事では、カスタムインターフェース「SendMessage」を定義し、ホストとなるMainActivityを仲介してデータを受け渡す、定番かつ推奨されるパターンを紹介します。 具体的には、タブで切り替えられる2つのフラグメントを用意し、1つ目のフラグメントで入力したテキストをボタン操作で2つ目のフラグメントに表示させるサンプルアプリを作成します。 ステップ1:新しいプロジェクトを作成する

  2. iPhoneからAndroidへ動画を移行する方法|画質を落とさず簡単に送れる方法まとめ

    「新しいHuaweiスマホを購入したのですが、古いiPhoneから新しいAndroidスマホに動画を直接送るにはどうすればいいでしょうか。iPhoneからAndroidへの動画の移し方を教えてください。」 iPhoneからAndroidへ乗り換える際、最も手間がかかる作業のひとつがデータの移行です。iOSとAndroidは異なるプラットフォームで動作しているため、動画などのデータを移すのは難しく感じられるかもしれません。しかし、適切なツールと正しい手順さえあれば、このプロセスは驚くほど簡単かつスムーズに行えます。 本記事では、元の画質を損なうことなくiPhoneからAndroidへ動画を送信で