最近,我正在开发餐厅订单管理应用程序。因此,我不得不每秒从后台服务器检查一次新订单。如果有新订单,将会有一个弹出通知。因此,我将Alarm Manager与广播接收器和意图服务一起使用来解决此问题。但是问题是有时运行良好,有时服务停止,无法运行。我该如何克服这个问题?我希望即使应用程序被终止,也要在后台运行一个连续的进程。我怎样才能做到这一点??
我附上我到目前为止尝试过的内容:
广播接收器
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"/>
请帮助,高度感谢您的帮助
取决于您的任务优先级是否可延期。对于可延期的任务,建议使用具有所需约束的workManager。对于即时任务,我们有多种选择,我推荐带通道的协程。