Search code examples
androidandroid-activitybroadcastreceiver

How to send and save string message in Activity from BroadcastReceiver


How to save string message from BroadcastReceiver and use saved variable in Activity? I'm finding only Toast.makeText examples. What i'm actually have: working, registered BroadcastReceiver. My app running in DocumentActivity, when i'm hitting Scan button on my DataCollectionTerminal (DTC on Android 7.0), DTC takes message and toast it. I can catch messages from DTC in opened EditText and save it onClick save button.

But what i'm need: Scan button pressed => DTC takes barcode message => send to Activity and save it to some variable => and i can use this var.value in whole Activity, set it TextView, write it to the txt document and etc.

DocumentActivity

class DocumentActivity : AppCompatActivity() {

private val customBroadcastReceiver = CustomBroadcastReceiver()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(exp..R.layout.activity_document)
}

override fun onResume() {

    super.onResume()
    registerReceiver(
        customBroadcastReceiver,
        IntentFilter ("com.xcheng.scanner.action.BARCODE_DECODING_BROADCAST")
    )
}

override fun onStop() {
    super.onStop()
    unregisterReceiver(customBroadcastReceiver)
}

fun saveMessage(mes: String){
    var code = mes
    Toast.makeText(applicationContext, code, Toast.LENGTH_SHORT).show()
    ...
}}

BroadcastReceiver

class CustomBroadcastReceiver : BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) {

    val type = intent.getStringExtra("EXTRA_BARCODE_DECODING_SYMBOLE")
    val barcode = intent.getStringExtra("EXTRA_BARCODE_DECODING_DATA")

    val sb = StringBuilder()
    sb.append("Type: $type, Barcode:$barcode\n")

    Toast.makeText(context, sb.toString(), Toast.LENGTH_SHORT).show()

    // Save mes, doesnt work
    DocumentActivity().saveCell(barcode)
}}

Solution

  • You are creating another object of DocumentActivity and saving the value in variable for that object, so it will not reflect in cuurent object. Try to make variable static and then update it from broadcasteceiver. For eg variable in DocumentActivity is barCodeVal so,

    in DocumentActivity

    companion object{
      var barcodeVal = //some default value
    }
    

    Then from broabcastreceiver

    DocumentActivity.barcodeVal = barcode