如何在MainActivity中创建和访问BroadcastReceiver ?(芬兰湾的科特林)



什么是正确的方式来创建和使用BroadcastReceiver为一个活动内部的警报管理器?

我确实看了一下以下答案,但我不清楚我是否需要注册广播接收器以及如何使用AlarmManager注册。此外,我不清楚我是否应该在OnCreate()函数内创建BroadcastReceiver或作为类变量。

kotlin中的广播接收器

Kotlin AlarmManager和BroadcastReceiver不工作

背景:

我正在尝试做一个应用程序:

  1. 在指定时间播放歌曲

  2. 更新歌曲下次播放的时间

我能够得到1)通过为BroadcastReceiver文件创建一个单独的文件来工作,因为通常是这样做的,但是我无法访问AlarmManager,因为它只在AppCompatActivity类中可用。我还尝试使用意图移回主活动并在那里设置新的警报,但这也确实有效,因为BroadcastReceiver没有上下文。

我现在试图有BroadcastReceiver内的MainActivity,但它没有被触发:

private lateinit var picker: MaterialTimePicker
private lateinit var alarmManager: AlarmManager
private lateinit var calendar: Calendar
val broadCastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var mp = MediaPlayer.create(context, R.raw.song_title)
mp.setVolume(1.0f, 1.0f)
mp.start()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var calendar = Calendar.getInstance()
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
val newDate = Calendar.getInstance()
newDate.add(Calendar.MINUTE, 1)
calendar[java.util.Calendar.HOUR_OF_DAY] = newDate.get(Calendar.HOUR_OF_DAY)
calendar[java.util.Calendar.MINUTE] = newDate.get(Calendar.MINUTE)
calendar[java.util.Calendar.SECOND] = 0
calendar[java.util.Calendar.MILLISECOND] = 0
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)

}

}

AlarmManager不仅可以在AppCompatActivity类中使用,而且可以从任何地方访问Context如下所示:

class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val alarmManager = context?.getSystemService(ALARM_SERVICE) as AlarmManager
}
}

调整这个答案后,我得到了它的工作:

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
var TAG = "check"
Log.i(TAG,"==============")
Log.i(TAG,"inside receiver")
Log.i(TAG,"==============")
}
}
this.registerReceiver(receiver, IntentFilter("TEST"))
val intent = Intent()
intent.action = "TEST"
val alarmManager = this.getSystemService(ALARM_SERVICE) as? AlarmManager
val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
val calendar = Calendar.getInstance()
calendar.add(Calendar.SECOND, 10)
alarmManager?.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)

}
}

我可以确认确实需要注册接收人。

相关内容

  • 没有找到相关文章

最新更新