安卓Kotlin共享数据与屏幕开机的intentfilter。

问题描述 投票:0回答:1
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)
android kotlin android-intent broadcastreceiver intentfilter
1个回答
1
投票

Intent.ACTION_SCREEN_ONIntent.ACTION_SCREEN_OFF 会由安卓系统发送,你没有办法将信息添加到意图中,当 BroadcastReceiver 触发回调 onReceive. 关于问题,我建议你把pinNo和isRemoteOn的一些信息保存到 SharedPreferences里面 onReceive 得过且过 SharedPreferences

© www.soinside.com 2019 - 2024. All rights reserved.