Search code examples
androidvariablesandroid-intentservicedestroy

Service binding and Two activities Strange case


I understand about the SERVICE and luckily my android project works well. Until today I realized there's some strange effect when the variable stored in my Service is not updating. Especially when I pressed back button and returning to that activity.

Scenario:

You run the project on real device. Automatically Activity-A will be opened. As the code below, once the binding is succeed you'll store your navigation variable. Then you go to Activity-B. And just like before, your navigation will be stored as well. Then after couple seconds, you pressed back button. Returning your frame into Activity-A. Then When go to Activity-B again from here. And checking the navigation variable. It is not "ACTIVITY-B" ! Why is that happened like this?

Every Activity has the following methods and variables:

// == this is important for every Service communication
private MainServices serviceWorks;
private Intent serviceIntent;
private boolean myBindingState = false;

// connect to the service
private ServiceConnection serviceConn = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName arg0, IBinder arg1) {
        MainBinder myBinder = (MainBinder) arg1;
        serviceWorks = myBinder.getService();
        myBindingState = true;

        serviceWorks.setActivity(Chat2Activity.this);

// store either ACTIVITY-A or ACTIVITY-B 
        serviceWorks.setMyNavigationPosition(Nav.ACTIVITY-A);
        serviceWorks.setCurrentContext(getApplicationContext());


    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        myBindingState = false;
    }
};

@Override
protected void onStart() {
    super.onStart();
    if (serviceIntent == null) {
        serviceIntent = new Intent(this, MainServices.class);
        bindService(serviceIntent, serviceConn, Context.BIND_AUTO_CREATE);
        startService(serviceIntent);
    }

}

// == this is important for every Service ommunication
@Override
protected void onStop() {
    super.onStop();
    try {
        stopService(serviceIntent);
        unbindService(serviceConn);
    } catch (Exception e) {

    }
}

how do i move from one activity to another? Using this code below:

// either Activity-A or B are stated called here
Intent i = new Intent(getApplicationContext(), ActivityA.class);
startActivity(i);

How to solve this case?


Solution

  • Try adding this code in both the activities.

    protected void onResume()
       {
          super.onResume();
          if (myBindingState==true)
          serviceWorks.setMyNavigationPosition("B"); //Or "A"
       }
    

    You may also move unbindService() to onDestroy() instead of onStop()