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

KotlinでAndroidサービスから通知を送信する方法を徹底解説!

この記事では、Kotlinを使ってAndroidのService(サービス)から通知(Notification)を送信する方法を、実際のサンプルコードとともにわかりやすく解説します。

作成するアプリの概要

画面のテキストボックスに入力した文字列を、フォアグラウンドサービス経由で通知として表示するシンプルなアプリです。サービスの開始・停止は、それぞれ専用のボタンから行えます。

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

Android Studioを起動し、メニューからFile → New Projectを選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。

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

res/layout/activity_main.xmlに以下のコードを追加します。テキスト入力用のEditTextと、「Start Service」「Stop Service」の2つのボタンを縦方向に配置しています。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Input" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="startService"
        android:text="Start Service" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="stopService"
        android:text="Stop Service" />
</LinearLayout>

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

src/MainActivity.ktに以下のコードを記述します。「Start Service」ボタンがタップされると、EditTextに入力された文字列をIntentのExtraに格納し、ContextCompat.startForegroundService()でサービスを起動します。「Stop Service」ボタンではstopService()を呼び出してサービスを停止します。

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
    lateinit var editText: EditText
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        editText = findViewById(R.id.editText)
    }
    fun startService(view: View) {
        val input: String = editText.text.toString()
        val serviceIntent = Intent(this, ExampleService::class.java)
        serviceIntent.putExtra("inputExtra", input)
        ContextCompat.startForegroundService(this, serviceIntent)
    }
    fun stopService(view: View) {
        val serviceIntent = Intent(this, ExampleService::class.java)
        stopService(serviceIntent)
    }
}

ステップ4:サービスクラス(ExampleService.kt)の作成

新しいクラス「ExampleService.kt」を作成し、以下のコードを追加します。

Android 8.0(APIレベル26)以降では通知チャンネルの登録が必須となるため、onCreate()内でNotificationChannelを作成しています。onStartCommand()では、MainActivityから渡された入力文字列を通知の本文に設定し、PendingIntentによって通知タップ時にアプリへ戻れるようにしたうえで、startForeground()により通知を表示しています。

import android.app.*
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
class ExampleService : Service() {
    private val channelId = "Notification from Service"
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate() {
        super.onCreate()
        if (Build.VERSION.SDK_INT >= 26) {
            val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel(
                    channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT
                )
            } else {
                TODO("VERSION.SDK_INT < O")
            }
            (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
                channel
            )
        }
    }
    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        val input = intent.getStringExtra("inputExtra")
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            0, notificationIntent, 0
        )
        val notification: Notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle("Example Service")
            .setContentText(input)
            .setSmallIcon(R.drawable.notification)
            .setContentIntent(pendingIntent)
            .build()
        startForeground(1, notification)
        return START_NOT_STICKY
    }
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }
}

ステップ5:AndroidManifest.xmlの編集

androidManifest.xmlに以下のコードを追加します。フォアグラウンドサービスを利用するため、<uses-permission>でFOREGROUND_SERVICE権限を宣言することが重要です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <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アイコンKotlinでAndroidサービスから通知を送信する方法を徹底解説!をクリックしてください。デバイス選択画面で接続したモバイル端末を選択すると、実機の画面にアプリが起動します。

KotlinでAndroidサービスから通知を送信する方法を徹底解説!

KotlinでAndroidサービスから通知を送信する方法を徹底解説!

  1. 【Android開発】AlarmManagerを使ってサービスを起動する方法を徹底解説

    この記事では、AndroidアプリにおいてAlarmManager(アラームマネージャー)を使用してサービス(Service)を起動する方法を、サンプルコードとともにステップ形式で解説します。指定した時刻に処理を自動実行したい場合や、バックグラウンドでの定期処理を実装したい場合に役立つテクニックです。実装の全体像本チュートリアルで作成するアプリは、以下の構成になっています。「Start Service Alarm」ボタン:3秒後にサービスを起動するアラームをセット「Cancel Service」ボタン:セット済みのアラームをキャンセルそれでは、順番に実装していきましょう。ステップ1:新規プロジ

  2. 【Android】JavaMail APIを使用してメールを送信する方法を解説

    はじめに この記事では、JavaMail APIを使用してAndroidアプリからメールを送信する方法を、ステップごとに詳しく解説します。画面に入力した宛先・件名・本文をもとに、GmailのSMTPサーバー経由でメールを送信するシンプルなサンプルアプリを作成していきます。 手順1:新規プロジェクトの作成 Android Studioを起動し、「File」→「New Project」を選択して、必要事項を入力して新しいプロジェクトを作成します。 手順2:レイアウトファイル(activity_main.xml)の作成 res/layout/activity_main.xmlに以下のコードを記述しま