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

【Android】通知ボタンをタップした後に通知パネルを閉じる方法

はじめに

本記事では、Androidで通知パネル(ステータスバーから下にスワイプして表示される領域)を、通知内のボタンがクリックされたタイミングで自動的に閉じる方法を解説します。ポイントは、Intent.ACTION_CLOSE_SYSTEM_DIALOGS をブロードキャストとして送信することです。あわせて、ボタンをタップすると通知を生成するサンプルアプリ全体の実装手順も順番に見ていきましょう。

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

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

手順2:レイアウトファイル(res/layout/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="通知を作成"
        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 に以下のコードを追加します。ボタンをタップすると通知チャネルを作成して通知を表示し、その直後に ACTION_CLOSE_SYSTEM_DIALOGS を送信することで、展開中の通知パネルを自動的に閉じられるようになります。

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.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);
                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);
                    mNotificationManager.createNotificationChannel(notificationChannel);
                }
                mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());

                // ★ここがポイント:通知パネルを閉じる
                Intent closePanel = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
                sendBroadcast(closePanel);
            }
        });
    }
}

通知パネルを閉じる仕組み

android.intent.action.CLOSE_SYSTEM_DIALOGS(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)は、通知シェードやシステムダイアログなど、ホーム画面以外のシステムUIを閉じさせるためのブロードキャストです。sendBroadcast() で送信すると、現在下ろされている通知パネルを閉じることができます。なお、このアクションはAndroid 12(APIレベル31)以降、サードパーティアプリからの利用が制限されている点には留意してください。

手順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スマートフォンをPCに接続しているものとします。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。デバイス一覧から接続した端末を選択すると、端末にアプリの初期画面が表示されます。

「通知を作成」ボタンをタップして通知を表示させてみてください。通知パネルを下ろした状態で処理が実行されると、パネルが自動的に閉じることを確認できます。

【Android】通知ボタンをタップした後に通知パネルを閉じる方法

  1. 【Android】ホームボタンの押下を検知する方法|onUserLeaveHint()の実装手順を解説

    はじめに:Androidでホームボタンは「上書き」できるのか? 結論から言うと、Androidではセキュリティ上の設計思想により、ホームボタンの動作そのものを完全に無効化したり乗っ取ったりすることはできません。これは、ユーザーがいつでもアプリから抜けられるようにするためのGoogleの意図的な仕様です。しかし、onUserLeaveHint()というコールバックメソッドを利用すれば、「ユーザーがホームボタンを押してアプリを離れようとした瞬間」を検知することは可能です。本記事では、ホームボタンが押されたタイミングでToastメッセージを表示するサンプルアプリの作成手順を、ステップごとにわかりやす

  2. 【Android】ボタンの角を丸くする方法を徹底解説!カスタムドローアブルで実装する手順

    このチュートリアルでは、Androidアプリでボタンの角を丸く表示する方法を、実際のコード例とともにわかりやすく解説します。カスタムドローアブル(Drawable)を活用することで、通常時・フォーカス時・押下時といったボタンの状態に応じた角丸デザインも柔軟に実現できます。 手順1:Android Studioで新規プロジェクトを作成する まずはAndroid Studioを起動し、メニューから「File → New Project」を選択して新しいプロジェクトを作成しましょう。必要な項目をすべて入力し、プロジェクトのセットアップを完了させてください。 手順2:レイアウトファイル(activit