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

【Android】通知の表示が許可されているか確認する方法と通知作成の実装手順

この記事では、Androidアプリにおいて通知の表示が許可されているかどうかを確認する方法と、NotificationBuilderを使って実際に通知を作成・表示する手順を、サンプルコード付きでわかりやすく解説します。

通知の表示が許可されているかを確認する方法

ユーザーがアプリの通知をオフにしている場合、コードが正しくても通知は端末に表示されません。そのため、通知を発行する前に許可状態をチェックしておくことが重要です。

確認には NotificationManagerCompat.areNotificationsEnabled() を使用します。

boolean isEnabled = NotificationManagerCompat.from(this).areNotificationsEnabled();

if (!isEnabled) {
    // 通知が無効になっている場合の処理
    // アプリの通知設定画面へ誘導するなどの対応を行う
}

このメソッドは、Android 8.0(APIレベル26)以降の通知チャンネルごとの設定も考慮して判定してくれるため、確実なチェックが可能です。通知が無効になっている場合は、Intentでシステムの通知設定画面へ誘導することで、ユーザー体験の向上につながります。

サンプルアプリ:ボタンをタップして通知を表示する

ここからは、実際に通知を作成するサンプルアプリを段階的に構築していきます。

ステップ1:新規プロジェクトの作成

Android Studioを開き、「File」→「New Project」を選択して、必要事項を入力し新しいプロジェクトを作成します。

ステップ2:レイアウトの定義(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"
    tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:onClick="createNotification"
        android:text="create notification" />

</RelativeLayout>

ステップ3:MainActivity.java の実装

ボタンがクリックされると呼び出される createNotification() メソッド内で、NotificationCompat.Builderを使って通知を組み立てます。Android 8.0以降では通知チャンネルの作成が必須となるため、SDKバージョンを判定して処理を分岐させている点に注目してください。

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;

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);
    }

    public void createNotification(View view) {
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(MainActivity.this,
                        default_notification_channel_id);
        mBuilder.setContentTitle("Notify Me \uD83D\uDE00");
        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());
    }
}

ステップ4:AndroidManifest.xml の設定

VIBRATEパーミッションを追加し、MainActivityをランチャーアクティビティとして登録します。

<?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」アイコンをクリックしてください。デバイス選択画面で自分のスマートフォンを選択すると、実機にアプリがインストールされて起動します。

アプリが起動したら「create notification」ボタンをタップします。ステータスバーに通知が表示され、通知をタップすると自動的に消える(setAutoCancel(true)の効果)ことが確認できます。もし通知が表示されない場合は、前述の areNotificationsEnabled() で許可状態を確認し、端末の設定から該当アプリの通知をオンにしてください。

  1. Androidでネットワーク接続の有無を確認する方法をステップ形式で解説

    本記事では、Androidアプリ上でインターネット接続(Wi-Fiまたはモバイルデータ通信)が利用可能かどうかをプログラムから判定する方法を、実際のサンプルコードとともに段階的に解説します。オフライン時のエラー処理やユーザーへの通知を実装したい場合に役立つ基本的なテクニックです。手順1:新規プロジェクトを作成するまず、Android Studioを起動し、メニューから「File」→「New Project」を選択して、必要な項目をすべて入力し、新しいプロジェクトを作成します。手順2:レイアウトファイル(activity_main.xml)を編集する次に、res/layout/activity_

  2. Androidアプリで使用するRAMの容量を確認するにはどうすればよいですか?

    このチュートリアルでは、Androidアプリが使用するRAMの容量を確認する方法を解説します。ActivityManagerクラスとRuntimeクラスを活用することで、デバイス全体のメモリ状況とアプリ自身のメモリ使用量を簡単に取得できます。実装手順ステップ1:新規プロジェクトの作成Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。ステップ2:レイアウトファイルの編集res/layout/activity_main.xml に以下のコードを追加します。<?x