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

Androidアプリのランチャーアイコンに通知バッジ(未読件数)を表示する方法

Androidアプリでは、通知が届いた際にホーム画面のランチャーアイコン上に未読件数を示す「バッジ」を表示できます。この記事では、NotificationCompat.BuildersetNumber()メソッドとsetBadgeIconType()メソッドを活用して、通知の件数をランチャーアイコンに表示する実装方法を、サンプルコードとともに段階的に解説します。

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

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:onClick="createNotification"
        android:text="create notification"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

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

src/MainActivity.javaに以下のコードを記述します。ボタンがタップされるたびにカウントが1ずつ増加し、その数がsetNumber()によって通知バッジとして反映される仕組みです。また、アプリを開いた際(onResume())にはカウントがリセットされます。

package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import static android.app.Notification.BADGE_ICON_SMALL;
public class MainActivity extends AppCompatActivity {
    static int count = 0;
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";
    @Override
    protected void onResume() {
        super.onResume();
        count = 0;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void createNotification(View view) {
        count++;
        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
        notificationIntent.putExtra("fromNotification", true);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), default_notification_channel_id);
        mBuilder.setContentTitle("My Notification");
        mBuilder.setContentIntent(pendingIntent);
        mBuilder.setContentText("Notification Listener Service Example");
        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);
        mBuilder.setBadgeIconType(BADGE_ICON_SMALL);
        mBuilder.setNumber(count);
        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に以下のコードを記述します。

<?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" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <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アプリのランチャーアイコンに通知バッジ(未読件数)を表示する方法

補足:バッジ表示はランチャーに依存する

ランチャーアイコンのバッジ表示は、端末のホームアプリ(ランチャー)側の実装に依存する点に注意してください。Android 8.0(APIレベル26)以降では、通知チャンネルとsetNumber()を組み合わせることで、多くの標準ランチャーが未読件数をバッジとして表示します。一方、対応していないランチャーでは数値が表示されない場合があります。そのようなケースでは、ShortcutBadgerなどのサードパーティ製ライブラリの利用も検討するとよいでしょう。


  1. Androidスマホでアプリのアイコンサイズを変更する方法【ランチャー・標準設定】

    最近のAndroidスマートフォンの多くは、ホーム画面のアイコンサイズが固定されています。しかし、「アイコンをもっと大きくして見やすくしたい」「逆に小さくして画面に多くのアプリを表示したい」と思ったことはありませんか?実は、一部のスマートフォンでは標準機能としてアイコンサイズを変更でき、設定メニューを探せばすぐに見つかります。 標準機能が用意されていない機種でも、サードパーティ製ランチャーをインストールすれば、簡単にアイコンサイズを変更できます。この記事では、両方の方法をわかりやすく解説します。 1. サードパーティ製ランチャーを試す ほとんどのサードパーティ製ランチャーには、アイコンサイズ

  2. 【Android】アプリアイコンバッジの有効化・無効化を切り替える方法

    Androidスマートフォンを使っている方なら、通知を受け取るとロック画面にアラートとして表示されることをご存じでしょう。ロックを解除して通知シェードを下にスワイプすれば、通知内容を簡単に確認できます。さらに、LEDライトを点灯させて通知をお知らせする機能を利用している方も多いはずです。しかし、アプリアイコンバッジですべての未読通知を確認したい場合、多くのAndroid端末ではこの機能がデフォルトで有効になっていません。アプリアイコンバッジ機能とは、各アプリのアイコン上に、そのアプリの未読通知件数を数字で表示する機能です。iPhoneユーザーにはおなじみの機能で、iOSでは標準搭載されています