Kotlinを使ってAndroidアプリの起動時にサービスを自動的に開始する方法
このチュートリアルでは、Kotlinを使用してAndroidアプリでデバイスの起動時にサービス(Service)を自動的に開始する方法を解説します。BOOT_COMPLETED ブロードキャストを受信する BroadcastReceiver と、バックグラウンドで動作する Service を組み合わせた基本的な実装手順を、ステップごとに見ていきましょう。
手順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" android:padding="4dp" 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" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Hello World" android:textColor="@android:color/background_dark" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout>
手順3:サービスクラスの作成(RunServiceOnBoot.kt)
新しいKotlinクラスを作成し、RunServiceOnBoot.kt という名前で以下のコードを記述します。このサービスは起動時にトーストを表示し、Handler を使って5秒間隔の定期処理を繰り返すシンプルな例です。
import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.util.Log
import android.widget.Toast
class RunServiceOnBoot : Service() {
private val TAG = "MyService"
private lateinit var handler: Handler
private lateinit var runnable: Runnable
private val runTime = 5000
override fun onCreate() {
super.onCreate()
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show()
Log.i(TAG, "onCreate")
handler = Handler()
runnable = Runnable { handler.postDelayed(runnable, runTime.toLong()) }
handler.post(runnable)
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onDestroy() {
handler.removeCallbacks(runnable)
super.onDestroy()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}
override fun onStart(intent: Intent?, startId: Int) {
super.onStart(intent, startId)
Log.i(TAG, "onStart")
}
}
手順4:ブロードキャストレシーバーの作成(StartAppOnBoot.kt)
続けて、新しいKotlinクラスを作成し、StartAppOnBoot.kt という名前で以下のコードを記述します。このレシーバーは、システムが送信する ACTION_BOOT_COMPLETED ブロードキャストを受信すると、MainActivity を起動します。
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class StartAppOnBoot : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (Intent.ACTION_BOOT_COMPLETED == intent!!.action) {
val i = Intent(context, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(i)
}
}
}
手順5:MainActivityの実装
src/MainActivity.kt に以下のコードを追加します。アクティビティが作成されたタイミングでサービスを開始しています。
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intent1 = Intent(this@MainActivity, RunServiceOnBoot::class.java)
startService(intent1)
}
}
手順6:マニフェストの設定
androidManifest.xml に以下のコードを追加します。ここでは、起動完了ブロードキャストを受け取るために必要な RECEIVE_BOOT_COMPLETED パーミッションの宣言、BOOT_COMPLETED および QUICKBOOT_POWERON を受信するレシーバーの登録、そしてサービスの宣言を行っています。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.q9"> <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> <receiver android:name=".StartAppOnBoot"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.QUICKBOOT_POWERON" /> </intent-filter> </receiver> <service android:name=".RunServiceOnBoot" /> </application> </manifest>
アプリの実行
それでは、アプリケーションを実行してみましょう。実際のAndroid端末をパソコンに接続しているものとします。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの実行アイコン
をクリックします。オプションからお使いのモバイルデバイスを選択すると、端末にデフォルトの画面が表示されます。

注意: 最良の結果を得るためには、お使いの実機でお試しください。
補足:Android 8.0以降での注意点
Android 8.0(APIレベル26)以降では、バッテリー消費を抑えるためのバックグラウンド実行制限が設けられており、状況によってはバックグラウンドサービスの開始が制限されることがあります。継続的に処理を行いたい場合は、startForegroundService() を使ってフォアグラウンドサービスとして実行するか、JobIntentService や WorkManager の利用を検討することをおすすめします。
-
【Android】デバイス起動時にアプリを自動起動させる方法を徹底解説
概要本記事では、Androidデバイスの電源投入・再起動が完了したタイミングで、アプリケーションを自動的に起動させる方法を解説します。BroadcastReceiverを使ってシステムが発行する「BOOT_COMPLETED」ブロードキャストを受け取り、そこからアクティビティを起動するのが基本的な仕組みです。実装手順ステップ1:新規プロジェクトの作成Android Studioを開き、File ⇒ New Project を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。ステップ2:レイアウトファイル(res/layout/activity_main.xml)の編集
-
【Android】ボタンをタップしてホーム画面へ遷移させる方法を解説
この記事では、Androidアプリ内のボタンをタップしたときに、端末のホーム画面(ランチャー)へ遷移させる方法を、サンプルコード付きでわかりやすく解説します。 仕組みのポイント ホーム画面への遷移には、IntentクラスのACTION_MAINアクションとCATEGORY_HOMEカテゴリを組み合わせます。これは「Androidシステムのホームアプリを起動してほしい」という意図をシステムに伝えるための標準的な手法で、特別なパーミッションを追加する必要はありません。 手順1:新しいプロジェクトを作成する Android Studioを開き、メニューから「File」→「New Project」を選