Androidで通知をタップした後に自動的に閉じる方法|setAutoCancel(true)の使い方を解説
このチュートリアルでは、Androidアプリで表示した通知を、ユーザーがタップした後に自動的に閉じる(ステータスバーから削除する)方法を解説します。
ポイントとなるのは NotificationCompat.Builder の setAutoCancel(true) メソッドです。この設定を行っておくと、通知がタップされた時点で自動的に通知が消えるようになります。
実装手順
ステップ1:新規プロジェクトを作成する
Android Studioで新規プロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目を入力してプロジェクトを作成しましょう。
ステップ2:res/layout/activity_main.xml にコードを追加する
まずは通知を作成するためのボタンを配置したレイアウトファイルを用意します。以下のコードを activity_main.xml に記述してください。
<?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:src/MainActivity.java にコードを追加する
次に、ボタンが押されたときに通知を生成し、タップされたら自動的に閉じる処理を実装します。setAutoCancel(true) をチェーンに含めている点に注目してください。
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)
.setAutoCancel(true)
.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());
}
});
}
}
補足: 本記事のコードは旧サポートライブラリ(android.support)を使用しています。現在の新規プロジェクトではAndroidXが標準となっているため、androidx.appcompat.app.AppCompatActivity や androidx.core.app.NotificationCompat に読み替えて利用してください。
ステップ4:AndroidManifest.xml を確認する
最後に、マニフェストファイルが以下のようになっていることを確認します。ランチャーアクティビティとして MainActivity が登録されていれば問題ありません。
<?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」アイコンをクリックします。接続したモバイルデバイスを選択すると、端末にアプリの初期画面が表示されます。

ボタンをタップして通知を表示し、その通知をタップすると、アプリが開くと同時に通知がステータスバーから自動的に消えることが確認できます。
setAutoCancel(true) の役割とは?
setAutoCancel(true) を呼び出すことで、ユーザーが通知をタップした際に、その通知が自動的に削除されます。この設定がない場合、通知はタップ後もステータスバーに残り続け、ユーザーが手動でスワイプして削除しなければなりません。
また、notify() の第一引数には (int) System.currentTimeMillis() を渡して、通知ごとに一意のIDを割り当てています。同じIDで通知を発行すると既存の通知が上書きされるため、複数の通知を扱う場合は毎回異なるIDを使うのがポイントです。
-
【Android】EditTextの外側をタップしたときにソフトキーボードを非表示にする方法
はじめにAndroidアプリでは、EditText(テキスト入力欄)への入力を終えた後もソフトキーボードが開いたままになっていると、操作性が損なわれることがあります。本記事では、InputMethodManagerを使ってソフトキーボードを非表示にする方法を、サンプルプロジェクトを通じてわかりやすく解説します。実装手順ステップ1:新規プロジェクトの作成Android Studioを起動し、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力し、プロジェクトのセットアップを完了させてください。ステップ2:レイアウトファイルの作成res/layo
-
Windowsのフィードバック通知ポップアップを完全に無効化する方法
Microsoftは、Windowsの利用体験について意見を求めるため、ときどきポップアップでフィードバックを依頼してきます。こうしたポップアップが煩わしく感じる場合は、一度の設定変更だけで簡単に表示されなくできます。 設定画面からフィードバック通知をオフにする手順 まず、「設定」>「プライバシー」>「フィードバックと診断」を開きます。次に、「フィードバックの頻度」というドロップダウンメニューから「しない(Never)」を選択してください。これだけの操作で完了です。以降、フィードバックを求めるポップアップは表示されなくなります。 なお、この設定を変更しても、Windowsフィードバ