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

ブロードキャストレシーバーでAndroid通知の開始・停止を制御する方法

このチュートリアルでは、BroadcastReceiver(ブロードキャストレシーバー)を使ってAndroidの通知を開始・停止する方法を解説します。サンプルとして、USB接続の状態変化を検知し、通知の表示と非表示を切り替えるアプリを作成していきます。

手順1:新規プロジェクトを作成する

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

手順2:activity_main.xmlにコードを追加する

res/layout/activity_main.xml に以下のコードを記述します。

<?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"
    android:padding="16dp"
    tools:context=".MainActivity" />

手順3:MainActivity.javaにコードを追加する

src/MainActivity.java に以下のコードを記述します。

package app.tutorialspoint.com.notifyme;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

手順4:USBStateReceiver.javaにコードを追加する

src/USBStateReceiver.java に以下のコードを記述します。このクラスが通知の表示・非表示を制御する中核となる部分です。

package app.tutorialspoint.com.notifyme;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class USBStateReceiver extends BroadcastReceiver {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";
    boolean connected = true;
    @SuppressLint("UnsafeProtectedBroadcastReceiver")
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, default_notification_channel_id);
        builder.setContentTitle("USB - Notification");
        String action = intent.getAction();
        Log.e("USB", action);
        assert action != null;
        builder.setContentText("Connected");
        builder.setSmallIcon(R.drawable.ic_launcher_foreground);
        builder.setAutoCancel(true);
        builder.setChannelId(NOTIFICATION_CHANNEL_ID);
        Notification notification = builder.build();
        NotificationManager notificationManager = (NotificationManager) context.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);
            assert notificationManager != null;
            notificationManager.createNotificationChannel(notificationChannel);
        }
        assert notificationManager != null;
        if (connected) {
            notificationManager.notify(1, notification);
            connected = false;
        } else {
            notificationManager.cancel(1);
            connected = true;
        }
    }
}

ポイントは connected フラグです。受信するたびにフラグを反転させることで、同じ通知IDに対して notify() で通知を表示したり、cancel() で通知を消したりできる仕組みになっています。また、Android 8.0(APIレベル26)以降では通知チャンネルの作成が必須のため、SDK_INT の判定を行ってチャンネルを生成しています。

手順5:AndroidManifest.xmlにコードを追加する

AndroidManifest.xml に以下のコードを記述します。ここでUSB接続状態のシステムブロードキャストを受信するためのレシーバーを登録します。

<?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>
        <receiver android:name=".USBStateReceiver">
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_STATE" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

アプリを実行してみよう

それでは実際にアプリを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続しているものとします。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーのRun(実行)アイコンをクリックしてください。デバイス選択画面で自分のスマートフォンを選択すると、端末にデフォルト画面が表示されます。

その後、USBケーブルの抜き差しを行うと、接続時に通知が表示され、再度イベントを受け取ると通知が自動的に消える動作を確認できます。

  1. Androidスマホのバッテリーを消耗するアプリを見つけて対処する方法

    スマートフォンのバッテリー寿命を維持することは、端末を快適に「持ち歩く」ために欠かせません。新しいアプリをいくつかダウンロードしただけで、バッテリーの減りが急激に悪化した経験はありませんか?幸い、どのアプリが最もバッテリーを消耗しているかを確認する方法があり、原因を把握すればバッテリーの持ち時間を取り戻せます。バッテリー消費の犯人を見つける方法Androidのバッテリー設定を活用するどのアプリがバッテリーに大きな負担をかけているかを確認するには、まず「設定」を開きます。通常は、アプリ一覧から「設定」を選択することでアクセスできます。表示されるオプション一覧の中から「バッテリー」を見つけて選択し

  2. デスクトップとAndroidでChrome通知をオフにする完全ガイド

    多くのWebサイトは、プッシュ通知を活用して最新情報を直接パソコンやスマートフォンに届けています。新しい記事や自分の投稿へのコメントを見逃さずに済むため、便利な機能ではあります。しかし、すべてのサイトからの通知を許可してしまうと、あっという間に通知が溢れてしまい、かえってストレスの原因になります。 この記事では、Google Chromeに届く通知を停止・管理する方法を、デスクトップ版とAndroid版それぞれの手順とともに詳しく解説します。 デスクトップ版Chromeで通知を無効にする方法 WindowsやmacOSのPCでChrome通知をオフにするには、ブラウザの設定画面から簡単に