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

Androidでプログラムから通知バーの通知を削除する方法

はじめに

本記事では、Androidアプリでステータスバー(通知バー)に表示した通知を、コードから動的に削除する方法を解説します。通知の作成には NotificationCompat.Builder を使用し、削除には NotificationManagercancel() メソッドを利用します。具体的な実装手順をサンプルコード付きで見ていきましょう。

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

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

手順2:res/layout/activity_main.xml の編集

以下のコードを res/layout/activity_main.xml に追加します。画面中央に「Create notification」ボタンを配置するシンプルなレイアウトです。

<?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:res/layout/custom_notification_layout.xml の作成

次に、カスタム通知用のレイアウトファイル res/layout/custom_notification_layout.xml に以下のコードを追加します。アプリのアイコン・タイトル・説明文を並べたデザインになっています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="96dp"
    android:padding="10dp">
   <ImageView
       android:id="@+id/image"
       android:layout_width="wrap_content"
       android:layout_height="fill_parent"
       android:layout_alignParentStart="true"
       android:layout_marginEnd="10dp"
       android:contentDescription="@string/app_name"
       android:src="@mipmap/ic_launcher" />
   <TextView
       android:id="@+id/title"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_toEndOf="@id/image"
       android:text="Testing"
       android:textColor="#000"
       android:textSize="18sp" />
   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/title"
       android:layout_marginTop="8dp"
       android:layout_toEndOf="@+id/image"
       android:hint="This is just testing notification"
       android:inputType="text"
       android:textSize="14sp" />
</RelativeLayout>

手順4:src/MainActivity の実装

MainActivity に以下のコードを追加します。実装のポイントは次のとおりです。

  • createNotification():カスタムビューをセットした通知を notify() で表示します。通知IDには System.currentTimeMillis() の値を使い、一意性を確保しています。
  • removeNotification()mNotificationManager.cancel(notificationId) を呼び出すことで、指定したIDの通知を通知バーから削除できます。これが本チュートリアルの核心部分です。
  • Android 8.0(APIレベル26)以降では通知チャネルの作成が必須のため、Build.VERSION.SDK_INT の判定を行っています。
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RemoteViews;
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());
    }
    NotificationManager mNotificationManager;
    int notificationId = 0;
    public void createNotification(View view) {
       RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
       mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
       NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
       mBuilder.setContent(contentView);
       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);
       }
       notificationId = (int) System.currentTimeMillis();
       assert mNotificationManager != null;
       mNotificationManager.notify(notificationId, mBuilder.build());
    }
    public void removeNotification(View view) {
       if (notificationId != 0)
           mNotificationManager.cancel(notificationId);
    }
}

手順5: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でプログラムから通知バーの通知を削除する方法

まとめ

通知の削除は、表示時に使用した通知IDを保持しておき、NotificationManager.cancel(id) を呼び出すだけで簡単に実現できます。また、サンプルのように setAutoCancel(true) を設定しておけば、ユーザーが通知をタップした際にも自動的に通知が消えるため、より自然なUXを提供できます。

  1. Androidスマホからスパイウェアを検出して削除する方法

    Androidスマホ・タブレットでスパイウェアを検出する方法 スパイウェアは「隠れること」を目的として設計されているため、発見が非常に困難です。アプリ一覧に「スパイウェア」という名前のアイコンが表示されることはありません。しかし、感染を見分けるためのサインは他にもいくつか存在します。それらを知っておけば、Android端末上のスパイウェアを見つけ出すことができます。 スマホに隠れたスパイアプリが仕込まれていないか確認するには、以下のポイントに注目しましょう。 原因不明の動作の遅さやクラッシュ。 アプリの起動に時間がかかる、OSの動きが不安定、アプリが頻繁にフリーズするなど、全体的に動作が重く

  2. Androidスマホからウイルス・マルウェアを削除する方法|症状別の対処法を徹底解説

    近年、Androidユーザーは急速に増加し、かつてWindowsパソコンでしか使えなかった機能がスマートフォンの世界にも広がりました。インターネットへの即時アクセスやオンラインアプリなど革新的な機能を手軽に楽しめる一方で、ウイルスやマルウェアの脅威も同時に拡大しています。「良いものには必ず影がある」という言葉の通り、高度化するAndroidデバイスの影こそがウイルスなのです。これらの厄介な存在はOS全体に悪影響を及ぼし、スマートフォンを台無しにしてしまいます。もしスマホがマルウェア攻撃の被害に遭っているなら、この記事を読んでAndroid端末からウイルスを取り除き、ウイルスによるポップアップ