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

【Android】InboxStyle(受信トレイ形式)の通知を実装する方法をステップ解説

はじめに

この記事では、AndroidアプリでInboxStyle(受信トレイ形式)の通知を実装する方法を、実際のコード例とともにわかりやすく解説します。InboxStyleは、Gmailのように複数行のテキストをまとめて表示できる通知スタイルで、メッセージや更新情報の一覧を通知領域に見せたい場合に非常に便利です。

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

    <Button
        android:id="@+id/btnCreateNotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_centerInParent="true"
        android:text="Create Notification" />

</RelativeLayout>

手順3:MainActivity.java を実装する

次に、src/MainActivity.java に以下のコードを記述します。ボタンがタップされると createNotification() メソッドが呼び出され、InboxStyleの通知が生成される仕組みです。

ポイントは mBuilder.setStyle(new NotificationCompat.InboxStyle()) の部分です。また、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;

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("My Notification");
        mBuilder.setStyle(new NotificationCompat.InboxStyle());
        mBuilder.setContentText("Notification Listener Service Example");
        mBuilder.setTicker("Notification Listener Service Example");
        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());
    }
}

補足: 上記コードはサポートライブラリ(android.support)を使用していますが、現在の新規プロジェクトではAndroidXが標準のため、androidx.core.app.NotificationCompatandroidx.appcompat.app.AppCompatActivity に置き換えて利用してください。また、InboxStyleaddLine() メソッドを使うと、通知に複数行のテキストを自由に追加できます。

手順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スマートフォンをパソコンに接続していることを前提としています。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続したモバイルデバイスを選択すると、スマートフォンの画面にアプリが表示されます。

【Android】InboxStyle(受信トレイ形式)の通知を実装する方法をステップ解説

【Android】InboxStyle(受信トレイ形式)の通知を実装する方法をステップ解説

まとめ

NotificationCompat.BuildersetStyle() メソッドに NotificationCompat.InboxStyle を渡すだけで、受信トレイ形式の通知を簡単に作成できます。addLine() を組み合わせれば、複数のメッセージを一覧表示する通知も実現できるので、メールアプリやSNSアプリなど、さまざまなシーンで活用してみてください。

  1. 【Android】スナックバー(Snackbar)の使い方をステップごとに解説

    このチュートリアルでは、Androidアプリでスナックバー(Snackbar)を使用する方法を、サンプルコードとともに段階的に解説します。スナックバーは画面下部に短いメッセージを一時的に表示できるUIコンポーネントで、Toastとは異なり「再試行(RETRY)」などのアクションボタンを組み込めるのが大きな特徴です。 手順1:新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:レイアウトファイル(activity_main.xml)を編集する

  2. 【Android】NavigationViewの実装方法をステップごとに解説

    この記事では、AndroidアプリでNavigationView(ナビゲーションビュー)を使用してドロワーメニューを実装する方法を、ステップごとに詳しく解説します。ハンバーガーアイコンから開閉できるサイドメニューは、多くのアプリで採用されている定番のUIです。ステップ1:新しいプロジェクトを作成するAndroid Studioを開き、File → New Project を選択して、必要な情報を入力し新しいプロジェクトを作成します。テンプレートには「Navigation Drawer Activity」を選ぶと、後の作業がスムーズになります。ステップ2:activity_main.xml にコ