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

Androidの通知にボタンを追加する方法!addAction()を使った実装手順をコード例付きで解説

はじめに

このチュートリアルでは、Androidの通知(Notification)に「Snooze(スヌーズ)」のようなアクションボタンを追加する方法を、実際のコード例とともにわかりやすく解説します。通知にボタンを追加するには、NotificationCompat.BuilderaddAction() メソッドと PendingIntent を使用します。

実装のポイント

  • addAction():通知にボタンを追加するメソッド。アイコン・ラベル・PendingIntent を指定します。
  • PendingIntent:ボタンがタップされたときに実行される処理をあらかじめシステムへ渡しておく仕組みです。
  • 通知チャンネル:Android 8.0(API 26)以降では、通知を表示するためにチャンネルの作成が必須です。

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

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

手順2:レイアウトファイル(activity_main.xml)の編集

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 に以下のコードを追加します。ボタンがタップされると、「Snooze」ボタン付きの通知が表示されます。通知チャンネルはAndroid 8.0以降でのみ生成すればよいため、バージョン判定を行っています。

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 snoozeIntent = new Intent(MainActivity.this, MainActivity.class);
                snoozeIntent.setAction("ACTION_SNOOZE");
                snoozeIntent.putExtra("EXTRA_NOTIFICATION_ID", 0);

                PendingIntent snoozePendingIntent =
                        PendingIntent.getBroadcast(MainActivity.this, 0, snoozeIntent, 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.addAction(R.drawable.ic_launcher_foreground, "Snooze", snoozePendingIntent);
                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());
            }
        });
    }
}

手順4:AndroidManifest.xml の設定

AndroidManifest.xml に以下のコードを追加します。バイブレーションを使用する場合のため、VIBRATE パーミッションも定義しておきましょう。

<?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の通知にボタンを追加する方法!addAction()を使った実装手順をコード例付きで解説

「Create Notification」ボタンをタップすると、通知領域に「Snooze」ボタン付きの通知が表示されます。

Androidの通知にボタンを追加する方法!addAction()を使った実装手順をコード例付きで解説

補足:AndroidXへの置き換え

本記事のサンプルコードは旧サポートライブラリ(android.support)を使用しています。最近のAndroid Studioで作成したプロジェクトでは、androidx.appcompat.app.AppCompatActivityandroidx.core.app.NotificationCompat など、AndroidXの対応クラスに読み替えてください。また、1つの通知に追加できるアクションボタンは最大3つまでという制限がある点にも注意しましょう。

  1. AndroidのPreferenceScreenにボタンを追加する方法をわかりやすく解説

    はじめに この記事では、Androidアプリの設定画面(PreferenceScreen)にボタンを追加する方法を、実際のコード例とともにステップごとに解説します。設定画面内のボタンは、通常のPreference要素としてXMLで定義し、Java側でクリックリスナーを設定することで、好きな動作を割り当てることができます。 ステップ1:新規プロジェクトの作成 まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトのセットアップを完了させてください。 ステップ2:レイアウトファイル(acti

  2. Android 8で通知をスヌーズする方法

    多くの人にとって、一日の最後のタスクは翌日のためにアラームをセットすることでしょう。しかし実際には、スヌーズボタンを何度も押した末に、ようやく温かい布団から這い出すというのが現実ではないでしょうか。意外にも、スヌーズとスヌーズの間のわずかな時間こそ、一番深い眠りが得られる瞬間だったりします。つまり、スヌーズ機能は私たちの生活に欠かせない大切な機能なのです。そこで本記事では、Android 8の新機能「通知のスヌーズ(Snooze Notifications)」について詳しく解説します。この機能を使えば、必要なときにスマートフォンの通知を一時的に非表示にできるようになります。通知をスヌーズするメ