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

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

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

このチュートリアルでは、Androidアプリのランチャー(ホーム画面のアプリアイコン)に通知の件数をバッジとして表示する方法を解説します。NotificationCompat.BuilderのsetNumber()メソッドとsetBadgeIconType()メソッドを組み合わせることで、未読通知の数をアプリアイコン上に表示できるようになります。

手順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:app="https://schemas.android.com/apk/res-auto"
   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に以下のコードを追加します。

package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.app.PendingIntent ;
import android.content.Intent ;
import android.os.Bundle ;
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);
   }
   @SuppressLint("WrongConstant")
      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()) ;
   }
}

コードのポイント

  • count変数:通知を作成するたびに+1され、バッジに表示する件数を管理します。
  • onResume():アプリを開いた時点でカウントを0にリセットし、通知を既読扱いにします。
  • setBadgeIconType(BADGE_ICON_SMALL):ランチャーに表示するバッジアイコンの種類を指定します。
  • setNumber(count):バッジとして表示する通知の件数を設定します。
  • 通知チャンネル:Android 8.0(APIレベル26)以降では、通知を表示するために通知チャンネルの作成が必要です。

手順4:AndroidManifest.xmlの編集

Manifests/AndroidManifest.xmlに以下のコードを追加します。VIBRATEおよびRECEIVE_BOOT_COMPLETEDのパーミッションを宣言しています。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
   package="com.app.sample">
   <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】アプリのランチャーに通知の件数(バッジ)を表示する方法

  1. FacebookでAndroidアプリを作成する方法|開発者サイトでの設定手順を徹底解説

    この記事では、FacebookでAndroidアプリを作成する方法について詳しく解説します。AndroidアプリとFacebookを連携させるには、Facebook開発者サイトでFacebookアプリを作成し、Facebook App IDを取得する必要があります。以下の手順に従って、順番に進めていきましょう。 準備:Facebook開発者サイトで新しいアプリを追加する まず、https://developers.facebook.com/ にアクセスし、「新しいアプリを追加」をクリックしてアプリの作成を開始します。 ステップ1:アプリ名とメールアドレスを入力する 指定されたフィールドに、作

  2. Android 8で通知をスヌーズする方法

    多くの人にとって、一日の最後のタスクは翌日のためにアラームをセットすることでしょう。しかし実際には、スヌーズボタンを何度も押した末に、ようやく温かい布団から這い出すというのが現実ではないでしょうか。意外にも、スヌーズとスヌーズの間のわずかな時間こそ、一番深い眠りが得られる瞬間だったりします。つまり、スヌーズ機能は私たちの生活に欠かせない大切な機能なのです。そこで本記事では、Android 8の新機能「通知のスヌーズ(Snooze Notifications)」について詳しく解説します。この機能を使えば、必要なときにスマートフォンの通知を一時的に非表示にできるようになります。通知をスヌーズするメ