override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
val filter = IntentFilter()
filter.addAction(Intent.ACTION_SCREEN_ON)
filter.addAction(Intent.ACTION_SCREEN_OFF)
// Here I want to send some data to MyBroadcastReceiver like .putExtra but how with IntentFilter???
registerReceiver(MyBroadcastReceiver(), filter)
return START_STICKY
}
Мне нужно отправить переменную, используя IntentFilter, как мы делаем с intent.putExtra, когда происходит включение / выключение экрана. Я попытался отправить данные отдельно, но из-за того, что широковещательный объект был убит, все его переменные сброшены.
class MyBroadcastReceiver : BroadcastReceiver() {
private var isRemoteOn: Boolean = false
private var pinNo = "-1"
override fun onReceive(context: Context, intent: Intent) {
if(intent.action.equals("is_remote_on")) {
var status = intent.extras?.get("status").toString()
isRemoteOn = if (status.equals("on")) true else false
Log.d("RemoteOnOff", isRemoteOn.toString())
}
else if(intent.action.equals("setPin")) {
Log.d("PinNo", pinNo.toString());
pinNo = intent.extras?.get("pinNo").toString();
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF) or intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.d("pinNo", pinNo.toString()) // This always -1 when Screen get on/off no matter what I set here
Log.d("isRemoteOn", isRemoteOn.toString()) // This always false when Screen get on/off even I have set it to true }
}
}
Вот как я пытался установить isRemoteOn и pinNo
val broadcastIntent = Intent()
broadcastIntent.action = "setPin"
broadcastIntent.putExtra("pinNo", "5")
broadcastIntent.setClass(this, MyBroadcastReceiver::class.java)
val broadcastIntent2 = Intent()
broadcastIntent2.action = "is_remote_on"
broadcastIntent2.putExtra("status", "on")
broadcastIntent2.setClass(this, MyBroadcastReceiver::class.java)