注意:目前是無法啟動畫面(Activity)的喔!
如果要在開機時自動啟動App的背景服務,進行如藍牙連線等動作,可以使用Receiver來觸發背景程式。
1.建立BroadcastReceiver
BootDeviceReceiver.kt
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
import com.orhanobut.logger.Logger
import com.lugia.tool.CheckServices
class BootDeviceReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (Intent.ACTION_BOOT_COMPLETED == action) {
Logger.d("開機完成 ACTION_BOOT_COMPLETED")
startService(context)
}
}
private fun startService(context: Context) {
try {
//檢查服務是否已開啟
if(!CheckServices.isServiceRunning(context, "com.lugia.services.BleService")){
Toast.makeText(context, "啟動服務", Toast.LENGTH_LONG).show()
val startServiceIntent = Intent(context, BleService::class.java)
context.startService(startServiceIntent)
}else{
Logger.d("BleService 服務已開啟")
}
} catch (ex: InterruptedException) {
Logger.e("startService", ex)
}
}
}
2.在AndroidManifest.xml註冊相關功能
新增權限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
把BootDeviceReceiver加到AndroidManifest裡面:
<application>
<receiver
android:name=".services.BootDeviceReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
接下來就可以重新開機試試看效果了,每種設備發出ACTION_BOOT_COMPLETED訊號的速度都不一樣,所以開機完成後須要等一下才會啟動我們的服務。
發佈留言