[英]Service binding and Two activities Strange case
I understand about the SERVICE and luckily my android project works well. 我了解SERVICE,很幸运,我的android项目运行良好。 Until today I realized there's some strange effect when the variable stored in my Service is not updating. 直到今天,我才意识到,存储在我的Service中的变量未更新时会产生一些奇怪的影响。 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. 自动打开活动-A 。 As the code below, once the binding is succeed you'll store your navigation variable. 如下代码所示,绑定成功后,您将存储导航变量。 Then you go to Activity-B . 然后您转到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. 将框架返回到活动A。 Then When go to Activity-B again from here. 然后,当再次从此处转到活动B时。 And checking the navigation variable. 并检查导航变量。 It is not "ACTIVITY-B" ! 不是“ 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? 如何解决这种情况?
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() 您也可以将unbindService()移至onDestroy()而不是onStop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.