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

Androidで通知をタップしたときにアクティビティを起動する方法

はじめに

このチュートリアルでは、ユーザーが通知をタップしたときにAndroidのアクティビティを起動する方法を解説します。通知と画面の遷移はPendingIntentを使って紐付けることで実現でき、通知タップ時に任意のアクティビティを開けるようになります。

ステップ1:新規プロジェクトの作成

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

ステップ2:レイアウトファイルの作成

res/layout/activity_main.xml に以下のコードを追加します。ここでは、通知を生成するためのボタンを1つ配置しています。

<?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.java の実装

src/MainActivity.java に以下のコードを追加します。ボタンがクリックされると通知が生成され、通知をタップするとPendingIntent経由でMainActivityが起動される仕組みです。

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.view.View;
import android.widget.Button;

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);
        Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
        btnCreateNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.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.setContentText("Notification Listener Service Example");
                mBuilder.setTicker("Notification Listener Service Example");
                mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
                mBuilder.setContentIntent(pendingIntent);
                mBuilder.setAutoCancel(true);
                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());
            }
        });
    }
}

コードのポイント

  • PendingIntent: 通知がタップされたときに実行される処理を事前に登録しておく仕組みです。ここではMainActivityを起動するIntentを渡しています。
  • フラグの設定: FLAG_ACTIVITY_CLEAR_TOP と FLAG_ACTIVITY_SINGLE_TOP を組み合わせることで、既に存在するアクティビティを再利用し、画面の重複スタックを防ぎます。
  • NotificationChannel: Android 8.0(APIレベル26)以降では通知チャンネルの作成が必須です。重要度に IMPORTANCE_HIGH を指定すると、ヘッドアップ通知として表示されます。
  • setAutoCancel(true): 通知をタップした後に、自動的に通知バーから通知を消すための設定です。

ステップ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端末をパソコンに接続している状態で、Android Studioのツールバーにある「Run」アイコンをクリックします。実行デバイスとして自分のスマートフォンを選択すると、端末に以下のようなデフォルト画面が表示されます。

Androidで通知をタップしたときにアクティビティを起動する方法

「Create Notification」ボタンをタップすると通知が表示され、その通知をタップするとMainActivityが起動します。

Androidで通知をタップしたときにアクティビティを起動する方法

  1. Androidで通知からサービスを開始するには?基本の手順とサンプルコードを解説

    この記事では、Androidアプリで通知からサービス(Service)を開始する方法を、サンプルコードとともにわかりやすく解説します。AlarmManagerとPendingIntentを組み合わせることで、毎日決まった時刻にサービスを自動起動し、通知を表示する仕組みを実装できます。 実装の全体像 今回作成するアプリは、ボタンをタップすると翌日の午前0時にサービスが起動されるようスケジュールされ、サービス側で通知チャンネルを作成して通知を表示します。手順は以下の5ステップです。 Android Studioで新規プロジェクトを作成する activity_main.xmlにボタンを配置する M

  2. 【Android】ボタンをクリックして新しいアクティビティを起動する方法

    このチュートリアルでは、Androidアプリでボタンをクリックした際に新しいアクティビティ(画面)を起動する方法を解説します。Intentを使った画面遷移の基本が学べる内容なので、Android開発初心者の方にもおすすめです。 実装手順 ステップ1:新規プロジェクトを作成する Android Studioを開き、「File」→「New Project」を選択して、必要な項目をすべて入力し、新しいプロジェクトを作成します。 ステップ2:activity_main.xmlにコードを追加する res/layout/activity_main.xml に以下のコードを追加します。画面中央にボタンを1つ