Невозможно обновить пользовательский интерфейс с помощью Broadcast Receiver (Kotlin) - PullRequest
1 голос
/ 01 ноября 2019

Я хотел обновить пользовательский интерфейс My MainActivity, когда Bluetooth включен / выключен

MainActivity

private val broadcastReceiver = Broadcast()
    open var bluetooth : ImageView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
        registerReceiver(broadcastReceiver, filter)
        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        bluetooth = findViewById(R.id.image_bluetooth)
        val bluetoothName = findViewById<TextView>(R.id.text_bluetooth_name)
        bluetoothName.text = bluetoothAdapter.name
        bluetooth?.setOnClickListener {
            if (!bluetoothAdapter.isEnabled) {
                val turnOn = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(turnOn, 0)
            } else {
                bluetoothAdapter.disable()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(broadcastReceiver)
    }

    fun enableBluetooth()
    {
        bluetooth?.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_bluetooth_enable_48dp))
    }
    fun disableBluetooth()
    {
        bluetooth?.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_bluetooth_disable_48dp))
    }

BroadcastReceiver

class Broadcast : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            val mainActivity = MainActivity()
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                when (intent?.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
                    BluetoothAdapter.STATE_OFF -> {
                        Toast.makeText(context, "Bluetooth Turned OFF", Toast.LENGTH_LONG).show()
                        mainActivity.disableBluetooth()
                    }
                    BluetoothAdapter.STATE_ON -> {
                        Toast.makeText(context, "Bluetooth Turned ON", Toast.LENGTH_LONG).show()
                        mainActivity.enableBluetooth()
                    }
                }

            }
        }
    }

После вызова onReceive в BroadcastReceiver, в методах enableBluetooth и disableBluetooth bluetooth значение возвращает значение null. Может ли кто-нибудь помочь преодолеть процесс? Заранее спасибо

1 Ответ

1 голос
/ 02 ноября 2019

В этом случае используйте метод OnActivityResult для обновления пользовательского интерфейса

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0 && bluetoothAdapter!!.isEnabled) {
            Toast.makeText(this, "Bluetooth Turned ON", Toast.LENGTH_LONG).show()
            image_bluetooth?.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_bluetooth_enable_48dp))
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...