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

Androidで通知からアクティビティを起動する方法【コード例で解説】

この記事では、Androidアプリで通知をタップしたときにアクティビティ(画面)を起動する方法を、実際のコード例とともに段階的に解説します。

全体の仕組み

通知からアクティビティを起動するには、PendingIntentを使用します。PendingIntentとは、通知がタップされたタイミングでシステム側から発行されるIntentを、あらかじめ登録しておく仕組みです。また、Android 8.0(APIレベル26)以降では通知チャンネル(NotificationChannel)の作成が必須となっているため、その処理もあわせて実装します。

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

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

ステップ2:レイアウトファイルにボタンを配置する

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

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    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="0dp"
        android:layout_height="wrap_content"
        android:text="Create notification"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>

ステップ3:MainActivity.javaに通知処理を実装する

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.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 intent = new Intent(MainActivity.this, MainActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(
                        MainActivity.this, 0, intent,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(MainActivity.this,
                                default_notification_channel_id)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentIntent(contentIntent)
                        .setContentTitle("Test")
                        .setContentText("Hello! This is my first push notification");

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

コードのポイント

  • PendingIntent.getActivity():通知タップ時にMainActivityを起動するIntentを登録しています。
  • setContentIntent():BuilderにPendingIntentをセットすることで、通知タップ時の遷移先を指定できます。
  • NotificationChannel:Android 8.0以降で必須のため、SDK_INTがO(API 26)以上の場合にのみチャンネルを作成しています。
  • notify():IDとして現在時刻を渡すことで、通知ごとに一意のIDを発行しています。

ステップ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">

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

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

Androidで通知からアクティビティを起動する方法【コード例で解説】


Androidで通知からアクティビティを起動する方法【コード例で解説】

Androidで通知からアクティビティを起動する方法【コード例で解説】

まとめ

通知からアクティビティを起動するには、PendingIntentを作成し、NotificationCompat.BuildersetContentIntent()に渡すだけで実現できます。Android 8.0以降では通知チャンネルの作成も必須なので、忘れずに実装しましょう。なお、本記事のコードは旧サポートライブラリ(android.support)を使用していますが、新しいプロジェクトではAndroidX(androidx.appcompatなど)への置き換えを推奨します。

  1. Androidでアクティビティからフラグメントへ変数を渡す方法を徹底解説

    はじめに この記事では、Androidアプリ開発においてアクティビティ(Activity)からフラグメント(Fragment)へ変数を渡す方法を、実際のコード例とともに段階的に解説します。 アクティビティからフラグメントへのデータ受け渡しには、Bundleを使うのが基本です。アクティビティ側でsetArguments()メソッドによりBundleをフラグメントにセットし、フラグメント側でgetArguments()メソッドを使って値を取り出します。 手順1:新規プロジェクトを作成する Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Projec

  2. Androidアプリでフラグメントからアクティビティのメソッドを呼び出す方法【サンプルコード付き】

    このチュートリアルでは、Androidアプリにおいてフラグメントからアクティビティのメソッドを呼び出す実装方法を解説します。フラグメントは単体では動作せず、必ずアクティビティ上に存在するため、getActivity()で親アクティビティの参照を取得し、適切な型にキャストすることで、アクティビティのpublicメソッドを直接呼び出すことができます。 実装手順 ステップ1:新規プロジェクトの作成 Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。 ステップ2:activ