Home > database >  Is it allowed to use a static (Companion) variable from an Android BroadcastReceiver's onReceiv
Is it allowed to use a static (Companion) variable from an Android BroadcastReceiver's onReceiv

Time:01-26

I want to communicate with a BroadcastReceiver to configure the functionality on the fly. The BcR is forwarding SMS' and I want to configure filters, enable, disable, ...

Currently, I am using a Companion object in my MainActivity to control the behavior. Is that a good Idea and is the configuration there "persistent", even over a restart of the phone? It seems to survive restarting the app on the phone.

This is, how the receiver uses the flags:

class SmsReceiver() : BroadcastReceiver() {
    private var mLastTimeReceived = 0L
    internal var active : Boolean = true
    init {
        active = MainActivity.smsActive
        Log.d(TAG, "SMS is active $active")
    }
[... onReceive uses the value of active ...]

This is the MainActivity:

class MainActivity : AppCompatActivity() {
[ ... simple functions ... ]

        // a button modifies the flags
        binding.fab.setOnClickListener { view ->
            smsActive = !smsActive
            Snackbar.make(view, "$smsActive", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }

[ ... more simple functions ... ] 

    // the companion with the control flags
    companion object {
        var smsActive: Boolean = true
    }
}

Update: I wanted to understand if I could loose contact to the MainActivity class itself, resulting in a ClassNotFound or NPE. The discussion in the answer provided me with enough insight to understand. The data will go away with the process if not persisted and reloaded, but the class itself will always be there when the BroadcastReceiver runs.

CodePudding user response:

Is that a good Idea

Probably not.

is the configuration there "persistent"

If you mean "stored on disk", then no.

even over a restart of the phone?

No.

It seems to survive restarting the app on the phone.

That will depend entirely on your definition of "restarting the app". The value held in heap space of a process, such as the value of a static var, will not survive termination of that process.

Using some form of singleton as a cache is perfectly reasonable, but the "source of truth" needs to be some form of persistent storage.

  • Related