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

【Android】クリックしても消えない通知を作成する方法をわかりやすく解説

このチュートリアルでは、Androidでユーザーがタップしても自動的に消えない通知を作成する方法を解説します。ポイントは、NotificationCompat.Builderに対してsetAutoCancel(false)を呼び出すことです。通常、通知はタップすると自動的に削除されますが、この設定を行うことで通知がステータスバーに残り続けます。

手順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.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
                Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
                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);

                // setAutoCancel(false) が今回のキーポイント:
                // 通知をタップしても自動的に削除されなくなる
                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id)
                                .setAutoCancel(false)
                                .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);

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

コードのポイント

  • setAutoCancel(false):通知をタップしても自動的に削除しないための設定。これが本記事の核心部分です。逆にtrueを指定すると、従来どおりタップ時に通知が消えます。
  • PendingIntent:通知がタップされたときにMainActivityを起動するために使用します。
  • NotificationChannel:Android 8.0(Oreo/API レベル26)以降では、すべての通知に通知チャンネルの割り当てが必須です。
  • IMPORTANCE_HIGH:重要度を高く設定することで、ロック画面や画面上部(ヘッドアップ通知)にも表示されやすくなります。

手順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」アイコンをクリックしてください。デバイスを選択して実行すると、モバイル端末に以下のようなデフォルト画面が表示されます。

【Android】クリックしても消えない通知を作成する方法をわかりやすく解説

画面上の「Create notification」ボタンをタップすると通知が表示されます。その通知をタップしても自動的には消えず、ステータスバーに残り続けることを確認できます。通知を削除したい場合は、通知をスワイプするか、クリアボタンで手動に消す必要があります。

  1. AndroidアプリでTextToSpeech(音声読み上げ)機能を実装する方法をわかりやすく解説

    このチュートリアルでは、AndroidアプリにTextToSpeech(音声合成・TTS)機能を実装し、入力したテキストを音声で読み上げる方法を解説します。サンプルでは、シークバーを使って音声のピッチ(声の高さ)とスピード(話す速さ)を調整できる、実用的な構成になっています。 手順1:Android Studioで新規プロジェクトを作成 Android Studioを起動し、メニューから File ⇒ New Project を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:レイアウトファイル(activity_main.xml)を編集 res/layou

  2. FacebookでAndroidアプリを作成する方法|開発者サイトでの設定手順を徹底解説

    この記事では、FacebookでAndroidアプリを作成する方法について詳しく解説します。AndroidアプリとFacebookを連携させるには、Facebook開発者サイトでFacebookアプリを作成し、Facebook App IDを取得する必要があります。以下の手順に従って、順番に進めていきましょう。 準備:Facebook開発者サイトで新しいアプリを追加する まず、https://developers.facebook.com/ にアクセスし、「新しいアプリを追加」をクリックしてアプリの作成を開始します。 ステップ1:アプリ名とメールアドレスを入力する 指定されたフィールドに、作