marisxanis
marisxanis

Reputation: 107

static variable doesn't modify java android

I have 2 broadcastReceivers and 1 simple class -simple class has 1 static variable -when setting static variable simpleClas.time from broadcastReceiver1, the varibale is set to the correct value -but when you try to access simpleClass.time from broadcastReceiver2, the static variable remains the same all the time, it remains in the init value. How is that thing possible? At the end is a static

class simpleClass{
public static long time = 0;
}

class broadCastReceiver1 extends BroadcastReceiver{
@Override
    public onReceive(){

     //do some stuff and do an update of time variable
      simpleClass.time = System.currentTimeMillis()/1000;

    }
}

class broadCastReceiver2 extends BroadcastReceiver{
@Override
    public onReceive(){

     //do some stuff and only Read the variable time that was previously modified by broadCastReceiver1 and print the reading

     System.out.println("new Value of time = " + simpleClass.time);
    }
}

assuming that order of events is: broadCastReceiver1 broadCastReceiver2

The value of time is read all the time to initial value 0; for the broadCastReceiver2 the variable is all the time at value 0, but in the simpleClass class, time variable is updated!!! you can do other operations in simpleClass with the new value of variable time.

Somehow broadCastReceiver2 sees only the init value of simpleClass.time. How come? can anyone explain?

Upvotes: 0

Views: 383

Answers (1)

Or Bar
Or Bar

Reputation: 1566

By default, broadCastReceivers run on a new process, therefore they can't share the same data.

You will need to change your manifest definitions to make them run on the same process by adding android:process="string" to the broadcast reciever definition

Upvotes: 2

Related Questions