This is making me a bit crazy.
I have the following Application:
Activity A -> Activity B -> Activity C
A is defined in the manifest as android:launchMode=”singleTask”
B starts C as follows:
Intent startActivity = new Intent();
startActivity.setClass(this,C.class);
startActivity.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(startActivity);
C talks back and forth with a remote system over a socket.
While C is communicating, the Back key is disabled. Here is C’s onKeyDown():
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (sessionActive() && (keyCode == KeyEvent.KEYCODE_BACK)) {
return false;
}
else if (!sessionActive() && (keyCode == KeyEvent.KEYCODE_BACK)){
Log.d("C","done talking to socket, got Back key, exit Activity");
/* delete data from an internal static object */
}
return super.onKeyDown(keyCode, event);
}
sessionActive() returns true if we are still talking over the socket and we want the Back key disabled.
When sessionActive() is false we are done talking and we WANT the Back key to exit Activity C.
The problem is, its not working. I’ve followed this via log messages and the 1st time sessionActivity() == false I do get the “done talking to socket” message so I KNOW I’m getting to the right place. But, I have to press Back a 2nd time in order to get Activity C to go away.
Any ideas?
UPDATE UPDATE:
I have tried both answers and have gotten the same confusing results.
Here is a bit of my logcat showing the execution of the diffent lifecycle methods. I have a number of questions interspersed in the logcat text.
C.onCreate()
C.onStart()
C.onResume()
C.onKeyDown() sessionActive()==false, keyCode = BACK
this should get us out but doesn't
C.finish() sessionActive is FALSE
shouldn't this go to onStop()?
C.onPause() sessionActive is FALSE
C.onRestart() sessionActive is FALSE <- ???????? onRestart?
C.onStart() sessionActive is FALSE <- ???????? onStart?
C.onResume() sessionActive is FALSE
C.onStop() sessionActive is FALSE <- this makes sense
C.onDestroy() sessionActive is FALSE <- so does this
C.onPause() sessionActive is FALSE <- ????????
C.onResume() sessionActive is FALSE
C.onKeyDown() sessionActive is FALSE, keyCode = BACK
this is 2nd back press that does exit
C.finish() sessionActive is FALSE
C.onPause() sessionActive is FALSE there is no onRestart here!!!!!!!!!
C.onStop() sessionActive is FALSE
C.onDestroy() sessionActive is FALSE
I don’t understand the flow of control. I would have thought finish() sent control to onDestroy() and we’d be done.
You can try: