Недавно я работал над приложением управления заказами в ресторане. Поэтому там я должен был проверять новый заказ с сервера на заднем плане каждую секунду. Если будет новый заказ, появится всплывающее уведомление. Поэтому для решения проблемы я использовал Alarm Manager с широковещательным приемником и сервисом намерений. Но проблема в том, что иногда он работает хорошо, а иногда служба останавливается, она не работает. Как я могу преодолеть эту проблему? Я хочу, чтобы непрерывный процесс работал в фоновом режиме, даже если приложение убито. Как я могу это сделать??
Я прилагаю то, что я пробовал до сих пор:
Broadcast Receiver
class NotificationReceiver:BroadcastReceiver() {
companion object{
const val TAG = "RECEIVER"
const val REQUEST_CODE=12345
}
override fun onReceive(p0: Context?, p1: Intent?) {
PreferenceUtils.getInstance().initPreferences(p0!!)
UtilMethods.printLog(TAG,"Receiver Triggered")
val i = Intent(p0, OrderNotificationService::class.java)
i.putExtra("foo", "bar")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
p0.startForegroundService(i)
} catch (e: Exception) {
e.printStackTrace()
}
} else {
try {
p0.startService(i)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
Intent Service
class OrderNotificationService : IntentService("OrderNotificationService") {
private var mAudioPlayer = AudioPlayer()
private lateinit var mVibrator: Vibrator
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
val CHANNEL_ID = "DEMO"
val channel = NotificationChannel(
CHANNEL_ID,
"Notification",
NotificationManager.IMPORTANCE_DEFAULT
)
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
channel
)
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build()
startForeground(10, notification)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
override fun onHandleIntent(intent: Intent?) {
myWork()
}
}
Регистрация с помощью alarmManager
val intent = Intent(applicationContext, NotificationReceiver::class.java)
val pIntent = PendingIntent.getBroadcast(this, NotificationReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT)
val firstMillis = System.currentTimeMillis()
val alarm = getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 60*1000, pIntent)
Манифест
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service
android:name=".backgrounds.OrderNotificationService"
android:exported="false"/>
<receiver
android:name=".backgrounds.NotificationReceiver"
android:exported="true"/>
Пожалуйста, помогите, любая помощь очень ценится