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

KotlinでAndroidアプリのランチャーに通知バッジ数を表示する方法を解説

KotlinでAndroidアプリのランチャーに通知数を表示する方法

このチュートリアルでは、Kotlinを使用してAndroidアプリのランチャーアイコンに通知の件数(バッジ)を表示する方法を、ステップごとにわかりやすく解説します。

ステップ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">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:text="Tutorials Point"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:onClick="createNotification"
      android:text="create notification" />
</RelativeLayout>

ステップ3:MainActivity.ktの実装

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

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
class MainActivity : AppCompatActivity() {
   var count = 0
   private val channelId = "10001"
   private val defaultChannelId = "default"
   override fun onResume() {
      super.onResume()
      count = 0
   }
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
   }
   fun createNotification(view: View) {
      count++
      val notificationIntent = Intent(applicationContext, MainActivity::class.java)
      notificationIntent.putExtra("fromNotification", true)
      notificationIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or
      Intent.FLAG_ACTIVITY_SINGLE_TOP
      val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0)
      val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as
      NotificationManager
      val builder = NotificationCompat.Builder(applicationContext, defaultChannelId)
      builder.setContentTitle("My Notification")
      builder.setContentIntent(pendingIntent)
      builder.setContentText("Notification Listener Service Example")
      builder.setSmallIcon(R.drawable.ic_launcher_foreground)
      builder.setAutoCancel(true)
      builder.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
      builder.setNumber(count)
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
         val importance = NotificationManager.IMPORTANCE_HIGH
         val notificationChannel = NotificationChannel(channelId,
         "NOTIFICATION_CHANNEL_NAME", importance)
         builder.setChannelId(channelId)
         notificationManager.createNotificationChannel(notificationChannel)
      }
      notificationManager.notify(System.currentTimeMillis().toInt(), builder.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.com.q11">
<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>

コードのポイント解説

  • setNumber(count):ランチャーアイコンに表示される通知の件数を設定します。ボタンが押されるたびにカウントが1ずつ増加します。
  • setBadgeIconType():バッジの表示形式を指定します。ここでは「BADGE_ICON_SMALL」を使用しています。
  • NotificationChannel:Android 8.0(APIレベル26)以降では通知の発行に通知チャンネルの作成が必須となるため、SDKバージョンを判定してチャンネルを生成しています。
  • onResume():アプリを開いたタイミングでカウントを0にリセットし、未読件数が正しく更新されるようにしています。

アプリの実行と動作確認

それでは、アプリケーションを実行してみましょう。ここでは、実際のAndroid端末がパソコンに接続されていることを前提としています。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーの実行アイコンKotlinでAndroidアプリのランチャーに通知バッジ数を表示する方法を解説をクリックします。リストからお使いのモバイルデバイスを選択すると、端末にデフォルト画面が表示されます。

KotlinでAndroidアプリのランチャーに通知バッジ数を表示する方法を解説

ボタンをタップして通知を複数回作成すると、ホーム画面のランチャーアイコンに通知件数がバッジとして表示されることを確認できます。

  1. 【Android開発入門】トースト(Toast)を表示する方法をステップ解説

    Androidでトーストを表示するには?この記事では、Androidアプリでトースト(Toast)を表示する方法を、実際のコード例とともにわかりやすく解説します。トーストとは、画面の下部に短時間だけ表示される小さなポップアップメッセージのことで、ユーザーへの簡単な通知やフィードバックに活用されます。それでは、具体的な手順を見ていきましょう。ステップ1:新規プロジェクトを作成するまず、Android Studioを起動し、メニューから「File」→「New Project」を選択して、必要な情報を入力して新しいプロジェクトを作成します。ステップ2:レイアウトファイルにコードを追加する次に、res

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

    Androidアプリのランチャーに通知件数(バッジ)を表示する方法このチュートリアルでは、Androidアプリのランチャー(ホーム画面のアプリアイコン)に通知の件数をバッジとして表示する方法を解説します。NotificationCompat.BuilderのsetNumber()メソッドとsetBadgeIconType()メソッドを組み合わせることで、未読通知の数をアプリアイコン上に表示できるようになります。手順1:新規プロジェクトの作成Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目をすべて入力してプロジ