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

InboxStyleを使ってAndroid通知のスタイルを設定する方法

Androidアプリで通知を表示する際、NotificationCompat.InboxStyleを使用すると、Gmailの受信トレイのように複数行のテキストをまとめて表示できる通知を作成できます。メールアプリやSNSなど、複数のメッセージを一覧形式で見せたい場合に非常に便利なスタイルです。

この記事では、InboxStyleを使った通知の実装方法を、実際のコード例とともにステップごとに解説します。

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

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

ステップ2:レイアウトファイル(activity_main.xml)の編集

次に、res/layout/activity_main.xmlに以下のコードを追加します。ここでは、通知を作成するためのボタンを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に以下のコードを追加します。ポイントはsetStyle()メソッドにNotificationCompat.InboxStyleのインスタンスを渡す部分です。これにより、通知がInboxStyleで表示されるようになります。

また、Android 8.0(APIレベル26)以降では通知チャンネルの作成が必須のため、Build.VERSION.SDK_INTでOSバージョンを判定し、チャンネルを作成する処理も組み込んでいます。

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

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

画面上の「Create Notification」ボタンをタップすると、InboxStyleが適用された通知がデバイスに表示されます。通知を展開すると、受信トレイ形式のスタイルが確認できるはずです。

InboxStyleを使ってAndroid通知のスタイルを設定する方法

InboxStyleを使ってAndroid通知のスタイルを設定する方法

  1. Androidで通知からサービスを開始するには?基本の手順とサンプルコードを解説

    この記事では、Androidアプリで通知からサービス(Service)を開始する方法を、サンプルコードとともにわかりやすく解説します。AlarmManagerとPendingIntentを組み合わせることで、毎日決まった時刻にサービスを自動起動し、通知を表示する仕組みを実装できます。 実装の全体像 今回作成するアプリは、ボタンをタップすると翌日の午前0時にサービスが起動されるようスケジュールされ、サービス側で通知チャンネルを作成して通知を表示します。手順は以下の5ステップです。 Android Studioで新規プロジェクトを作成する activity_main.xmlにボタンを配置する M

  2. 【Android開発】Switchウィジェットのスタイルをカスタマイズする方法を徹底解説

    Android Switchウィジェットのスタイルをカスタマイズする方法 このチュートリアルでは、AndroidアプリのSwitch(スイッチ)ウィジェットの見た目を自由にカスタマイズする方法を紹介します。thumb(つまみ)とtrack(レール)に独自のDrawableを指定することで、ON/OFFの状態に応じてデザインが切り替わるオリジナルスイッチを作成できます。 ステップ1:新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目を入力して、新しいプロジェクトを作成しましょう。 ステップ2:レイアウトフ