简体   繁体   中英

Android: can I put Global Variables in BroadCastReceiver?

I have 2 classes that I want them interacting each other:

First is Receiver.java :

public class Receiver extends BroadcastReceiver{
    private int var = 0;

    public void onReceive(Context context, Intent intent) {
        //Bunch of codes here
        method();
        //use var to do something}

    private void method() {
        //do something}

    public void setVar(int i) {
         var= i; }
}

Then I have another class that I hope to use to change the variable in Receiver , MainActivity.java :

public class MainActivity extends AppCompatActivity {

    private Receiver receiver;

    protected void onCreate(Bundle savedInstanceState) {
        receiver.setVar; 
        //Bunches of other codes 
}

The Receiver class listen to SMS message and respond, it extends BroadcastReceiver .

The MainActivity class change setting in Receiver class.

Since the original code put all variables inside the onReceive() :

  • Will I be able to change variable var in the Receiver class if I put it outside of the method?

  • Can MainActivity access and change variable in the Receiver class?

  • Does the method() within Receiver class work?

The answer below is valid only for a BroadcastReceiver that is to be instantiated and registered/unregistered programmatically within an Activity as OP asked .

The answer won't work for a BroadcastReceiver that is to be declared within AndroidManifest and instantiated by the system, because once onReceive() returns the receiver is considered to be no longer active and a new instance will be created next time.


Receiver is a regular Java object, so

Will I be able to change variable var in the Receiver class if I put it outside of onReceive() ?

Yes. var is a class member of Receiver class.

Can MainActivity access and change variable in the Receiver class?

Yes. MainActivity has the receiver reference to a Receiver class instance.

Does the method() within Receiver class work?

Yes. You'll be able to call it after the receiver initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM