【问题标题】:Android Kotlin Sharing data with screen on/off intentfilterAndroid Kotlin 与屏幕开/关 Intentfilter 共享数据
【发布时间】:2020-08-18 08:14:48
【问题描述】:
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
    }

当屏幕开/关发生时,我需要像使用 intent.putExtra 一样使用 IntentFilter 发送一个变量。 我曾尝试单独发送数据,但由于广播对象被杀死,其所有变量都会重置。

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】:

    Intent.ACTION_SCREEN_ONIntent.ACTION_SCREEN_OFF将由Android系统发送,当BroadcastReceiver触发回调onReceive时,您无法向intent添加信息。关于问题,我建议您将有关 pinNo 和 isRemoteOn 的一些信息保存到SharedPreferences。在onReceive 里面你可以通过SharedPreferences 得到它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多