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

Android NotificationBuilderの実装例:通知を作成する方法を解説

このチュートリアルでは、AndroidのNotificationBuilderを使って通知(Notification)を作成する方法を、サンプルコード付きで解説します。初心者の方でも手順どおりに進めれば、簡単に通知機能を実装できます。

ステップ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>

このレイアウトはシンプルで、画面中央に配置された「create notification」というボタンが1つあるだけです。このボタンがタップされると、createNotificationメソッドが呼び出される仕組みになっています。

ステップ3:MainActivityの実装

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

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

このコードでは、NotificationCompat.Builderを使って通知のタイトル・本文・アイコンを設定し、通知を構築しています。setAutoCancel(true)を指定することで、ユーザーが通知をタップした際に自動的に通知が消えるようになります。

また、Android 8.0(APIレベル26)以降では通知チャンネルの作成が必須となるため、OSバージョンを判定し、該当する場合のみNotificationChannelを生成・登録しています。重要度にIMPORTANCE_HIGHを指定することで、ヘッドアップ通知として目立つ形で表示されます。

ステップ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">
    <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>

ここでは、通知時に振動させるための「VIBRATE」パーミッションを宣言し、MainActivityをランチャーアクティビティとして登録しています。

アプリの実行

それでは、アプリケーションを実行してみましょう。実際のAndroidスマートフォンがパソコンに接続されているものとします。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続済みのモバイルデバイスを選択してアプリを実行すると、端末の画面にボタンが表示されたホーム画面が現れます。

ボタンをタップすれば、「Notify Me 😀」「Something important!」という内容の通知がステータスバーに表示されます。通知をタップまたはスワイプすると、自動的に消えることも確認してみてください。

  1. 【Android入門】ToggleButton(トグルボタン)の使い方と実装例をわかりやすく解説

    ToggleButtonとは 実装例に入る前に、AndroidにおけるToggleButton(トグルボタン)について簡単に確認しておきましょう。ToggleButtonはButtonビューを拡張したウィジェットで、ボタンの状態を「チェック済み(ON)」と「未チェック(OFF)」の2つの状態として表現できます。設定の有効・無効を切り替えるなど、オン・オフ操作が必要な場面で活躍するUIパーツです。 ここからは、AndroidアプリでToggleButtonを実装する具体的な手順をステップごとに見ていきます。 ステップ1:新規プロジェクトを作成する Android Studioで新しいプロジェクト

  2. 【初心者向け】Android Studioで学ぶフラグメント(Fragment)の使い方:サンプルコード付きチュートリアル

    はじめにこのチュートリアルでは、Android Studioを使ってフラグメント(Fragment)を実装する方法を、実際のサンプルコードとともにステップごとに解説します。フラグメントはアクティビティの中に配置できる再利用可能なUI部品で、ボタンの操作に応じて画面の一部だけを切り替えたい場合などに非常に便利です。本記事で作成するのは、2つのボタンをタップすると、それぞれ異なるフラグメントが表示されるシンプルなアプリです。ステップ1:新規プロジェクトを作成するまず、Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項