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

【Android】通知タップ時に新しいインテントを生成せず既存のActivityを再開する方法

はじめに

Androidアプリでプッシュ通知を実装する際、通知をタップするたびに新しいActivityが立ち上がってしまうという問題に直面することがあります。本記事では、通知タップ時に新しいインテントを生成するのではなく、すでに起動している既存のActivityを再表示(再開)させる方法を、サンプルコード付きで解説します。

鍵となるのは、通知用のIntentにFLAG_ACTIVITY_CLEAR_TOPFLAG_ACTIVITY_SINGLE_TOPを設定することです。この2つのフラグを組み合わせることで、バックスタックに同じActivityが存在する場合には新規インスタンスを作成せず、既存のものがそのまま再利用されるようになります。

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

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

手順2:activity_main.xmlにボタンを配置

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 notificationIntent = new Intent(MainActivity.this, MainActivity.class);
                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")
                        .setContentIntent(resultIntent)
                        .setStyle(new NotificationCompat.InboxStyle())
                        .setContentText("Hello! This is my first push notification");
                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());
            }
        });
    }
}

このコードで最も重要なのは、次の1行です。

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

FLAG_ACTIVITY_SINGLE_TOPは、対象のActivityがすでにスタックの最前面にある場合に新しいインスタンスを作らないことを示します。また、FLAG_ACTIVITY_CLEAR_TOPは、対象のActivityより上位に積まれているActivityをすべて破棄することを意味します。この2つを組み合わせることで、通知をタップしても既存のActivityがそのまま再開され、onCreate()の代わりにonNewIntent()が呼び出されるようになります。

手順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でプロジェクト内のいずれかのActivityファイルを開いた状態で、ツールバーの「Run」アイコンをクリックします。デバイスとして自分のスマートフォンを選択して実行すると、端末に以下のような初期画面が表示されます。

【Android】通知タップ時に新しいインテントを生成せず既存のActivityを再開する方法

画面上の「Create notification」ボタンをタップして通知を発行し、その通知をタップしてみてください。新しいActivityが起動されることなく、既存の画面がそのまま再表示されれば成功です。これにより、不要なインスタンスの生成を防ぎ、メモリの無駄遣いや意図しない画面の重複を回避できます。

  1. 【Android】ステータスバーの通知を端末の再起動後も維持する方法を解説

    はじめに Androidアプリで表示したステータスバーの通知は、端末を再起動すると消えてしまいます。本記事では、BroadcastReceiverとRECEIVE_BOOT_COMPLETED権限を組み合わせることで、端末の再起動後もステータスバー通知を自動的に復元・維持する方法を、サンプルコード付きで段階的に解説します。 ステップ1:新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。 ステップ2:レイアウトファイルを編集する res/layout

  2. Androidでインテントを使用して電話をかける方法【サンプルコード付き】

    この記事では、Androidアプリからインテント(Intent)を使用して電話をかける方法を解説します。ACTION_DIALアクションを利用することで、端末のダイヤラー画面を起動し、指定した電話番号を自動入力した状態で表示できます。 ステップ1:新規プロジェクトの作成 Android Studioを開き、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力し、プロジェクトのセットアップを完了させましょう。 ステップ2:レイアウトファイルの編集 res/layout/activity_main.xmlに以下のコードを追加します。ここでは、タッ