Androidで通知が表示中かキャンセル済みかを確認する方法【サンプルコード付き】
この記事では、Androidアプリで通知が現在表示されているのか、すでにキャンセル(削除)されているのかをプログラムから確認する方法を解説します。
Androidには通知の表示状態を直接問い合わせるシンプルなAPIが用意されていないため、ここでは PendingIntent の存在有無を利用したテクニックを紹介します。
実装の全体像
作業の流れは以下のとおりです。
- Android Studioで新規プロジェクトを作成する
- レイアウトに「通知作成ボタン」を配置する
- MainActivityに通知の生成と表示状態チェックのロジックを実装する
- AndroidManifest.xmlを設定する
ステップ1:新規プロジェクトの作成
Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目を入力して、新しいプロジェクトを作成しましょう。
ステップ2:レイアウトファイル(activity_main.xml)
res/layout/activity_main.xml に以下のコードを記述します。画面中央に「Create notification(通知を作成)」ボタンを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"
tools:context=".MainActivity">
<Button
android:onClick="createNotification"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="16dp"
android:text="Create notification" />
</RelativeLayout>
ステップ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.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
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);
onNewIntent(getIntent());
}
public void createNotification(View view) {
if (isNotificationVisible()) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
mBuilder.setContentTitle("Notify Me");
mBuilder.setContentText("Something important!");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
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());
}
}
private boolean isNotificationVisible() {
Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
PendingIntent test = PendingIntent.getActivity(
MainActivity.this, 123, notificationIntent,
PendingIntent.FLAG_NO_CREATE);
return test != null;
}
}
コードのポイント:isNotificationVisible() の仕組み
通知の表示状態を判定しているのが、privateメソッドの isNotificationVisible() です。
- PendingIntent.FLAG_NO_CREATE を指定して PendingIntent.getActivity() を呼び出すと、同じIntentとrequestCode(ここでは123)を持つPendingIntentがまだ存在しない場合に null が返ります。
- この戻り値がnullかどうかを調べることで、「通知に紐づくPendingIntentが既に存在するか」、すなわち通知が表示中かどうかを間接的に判定できます。
実際のアプリで使う場合は、通知側にも同じIntent・requestCodeで生成したPendingIntentを setContentIntent() でセットしておくと、判定と実通知が正しく対応します。また、「未表示のときだけ新規作成する」という条件(if (!isNotificationVisible()))にすれば、ボタンの連打などによる重複通知を防止できます。
補足として、API 23(Android 6.0)以降では NotificationManager.getActiveNotifications() を使うことで、システムに登録されている通知の一覧を直接取得できます。androidx環境では NotificationManagerCompat.getActiveNotifications() も利用可能です。要件に応じて使い分けるとよいでしょう。
ステップ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スマートフォンをPCに接続しているものとして説明します。
- Android Studioでプロジェクト内のアクティビティファイルを開きます。
- ツールバーの「Run ▶」アイコンをクリックします。
- 候補から接続済みのモバイルデバイスを選択して実行します。
正常にビルドされると、端末にアプリのデフォルト画面が表示されます。ボタンをタップして通知を作成し、その後通知をスワイプで削除してから再度ボタンを押せば、表示状態の判定処理の動きを確認できます。
-
Android EditTextが空かどうかを確認する方法【サンプルコード付きで解説】
このチュートリアルでは、Androidアプリ開発においてEditText(テキスト入力フィールド)が空かどうかを判定する方法を、実際にサンプルプロジェクトを作りながら段階的に解説します。ユーザー入力のバリデーションはアプリ開発の基本であり、空の入力を事前にチェックすることで、予期しないクラッシュや不正なデータ登録を防ぐことができます。 ポイント:TextUtils.isEmpty()メソッドを使う EditTextの内容が空かどうかを確認する最もシンプルな方法は、android.text.TextUtilsクラスが提供するisEmpty()メソッドを利用することです。このメソッドは、渡された
-
Androidの没入モード(イマーシブモード)とは?設定方法とおすすめアプリ5選
Androidスマートフォンは年々大型化が進んでいます。しかし、せっかくの大画面体験も、ナビゲーションバーやステータスバーが画面を占有してしまうと、動画視聴やゲームなどが台無しになってしまうことがあります。そこで気になるのが「これらのバーを消すことはできるのか?」という疑問です。 標準設定では難しい場合が多いですが、一部のアプリを使えば没入モード(イマーシブモード)を有効化できます。本記事では、Androidで没入モードを実現するためのおすすめアプリを詳しく紹介します。 Androidで没入モードを有効にする方法 ここでは、Android向けの代表的な没入モード対応アプリを5つピックアップしま