0

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)
}}
Sektor
  • 47
  • 2
  • 5

1 Answers1

0

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
Amit Tiwary
  • 787
  • 1
  • 8
  • 16
  • Thank you for answer. Can i call some function from onReceive? I mean everytime when message is received i need to run some function thats check and write barcodeVal to the text file. – Sektor Nov 19 '19 at 05:18
  • I find the answer from: https://stackoverflow.com/a/22241844/8315239 Created second BCReceiver and catching BCmessage from first – Sektor Nov 19 '19 at 05:35
  • yes, make that function static(write inside companion object block). If you think answer is helpful then accept it as answer. Of course, you can use another broadcast too. – Amit Tiwary Nov 19 '19 at 05:35