Androidアプリで数秒後に通知を自動的に消す(クリアする)方法
はじめに
このチュートリアルでは、Androidで通知を表示した後、一定時間(数秒)が経過したら自動的に通知を消去(クリア)する方法を解説します。
ポイントは、HandlerクラスのpostDelayed()メソッドを使い、指定した遅延時間の後にNotificationManagerのcancel()を呼び出すことです。これにより、ユーザーが手動で通知を削除しなくても、アプリ側で自動的に通知を消せるようになります。
手順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.Handler;
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");
final 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);
}
final int notificationId = (int) System.currentTimeMillis();
assert mNotificationManager != null;
mNotificationManager.notify(notificationId, mBuilder.build());
Handler h = new Handler();
long delayInMilliseconds = 5000;
h.postDelayed(new Runnable() {
public void run() {
mNotificationManager.cancel(notificationId);
}
}, delayInMilliseconds);
}
});
}
}コードのポイント
- 通知IDの一意な生成: System.currentTimeMillis() の戻り値を通知IDとして使用することで、複数の通知が重なってもそれぞれ個別に管理できます。
- Android 8.0(API 26)以降への対応: Build.VERSION.SDK_INT をチェックし、Oreo以降では通知チャンネル(NotificationChannel)を作成してから通知を表示します。
- 自動消去の仕組み: HandlerのpostDelayed()に5000ミリ秒(5秒)を指定することで、5秒後にcancel(notificationId)が呼ばれ、通知が自動的に消去されます。この値を変更すれば、消えるまでの時間を自由に調整できます。
手順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」アイコンをクリックします。表示された選択肢から接続中のモバイルデバイスを選択すると、端末にアプリの初期画面が表示されます。
ボタンをタップして通知を表示させると、約5秒後に通知が自動的に消えることが確認できます。

まとめ
本記事では、HandlerクラスのpostDelayed()メソッドとNotificationManagerのcancel()を組み合わせることで、Androidの通知を数秒後に自動的に消去する方法を紹介しました。一時的なお知らせやタイマー系アプリなど、一定時間後に不要になる通知を実装したい場合にぜひ活用してみてください。
-
Androidでリマインダー通知を実装する方法を初心者向けに解説
この記事では、Androidアプリで毎日決まった時刻に通知を表示する「リマインダー通知」の実装方法を、サンプルコードとともにステップごとに解説します。AlarmManagerとServiceを組み合わせることで、アプリが起動していなくても指定時刻に通知を届けられる仕組みを作れます。全体の仕組み本サンプルでは、以下の流れでリマインダー通知を実現します。1. 画面上のボタンをタップすると、翌日の午前0時に通知を発行するようAlarmManagerに登録します。2. 指定時刻になるとシステムがNotifyService(Serviceクラス)を起動します。3. Service内でNotificati
-
Androidのキャッシュをクリアする方法|手動・アプリを使った簡単な削除手順を徹底解説
記事のポイント:スマートフォンに溜まった不要なデータは、ストレージ容量を圧迫します。本記事では、Androidのキャッシュを「Smart Phone Cleaner」を使って素早く簡単に削除する方法と、手動でクリアする方法を詳しくご紹介します。 スマートフォンは長く使うほど不要なデータが蓄積され、端末のパフォーマンスが徐々に低下していきます。Androidの動作が重くなったと感じたら、まずは不要なファイルの整理から始めましょう。ジャンクファイルや一時ファイルだけでなく、キャッシュも併せて削除することが大切です。キャッシュは大量のストレージを占有する原因になるため、正しい削除方法を知っておきま