How to "return" to an activity (Or how to terminate an activity)?

by monkey.jsun » Tue, 20 May 2008 06:10:56 GMT

Sponsored Links
 I created a single-activity application that spawns a thread and binds
to a socket. For demo purpose, I need to switch to other application
through "return to home" key.  After that I like to switch back to the
original application.

I tried to click on my application again. Apparently the onCreate() is
invoked again, and the newly spawned thread will fail to bind to the
socket. That, (plus the output from "ps"), seems to suggest the
previous instance still exists.

How can I go back to the previous instance?

Alternatively, I was thinking whenever my application becomes
invisible I can try to terminate my application completely, instead of
letting hang around and causes problem next time I click the app
again.  How do I do that?

Would appreciate if you cc your reply to me directly.




How to "return" to an activity (Or how to terminate an activity)?

by Mark Murphy » Tue, 20 May 2008 12:03:37 GMT


If by "click on my application again", you mean you clicked on your icon 
in the launcher, by default that should create another instance of your 
activity process. In that respect, the launcher works the same as 
launchers in other OSes.

The "home" key brings up the Launcher activity and puts it at the top of 
the activity stack. Pressing the back button should eventually return 
you to your existing activity instance.

If you only want at most one instance of your activity running, you 
probably want to take a look at the android:launchMode attribute of the 
<activity> element of your AndroidManifest.xml file: #AndroidManifestActivity_launchMode

You'd want to set android:launchMode to singleTop, singleTask, or 
singleInstance, depending on what you're trying to achieve.

If you don't need the socket connection when you're not visible, I'd 
drop the socket in onPause() and bind in onResume(): #ActivityLifecycle

If you really want to close your activity, call finish() on the 
activity, and that will have it close up shop.

Mark Murphy (a Commons Guy) 
The Busy Coder's Guide to Android Development -- coming in June 2008!


Sponsored Links

How to "return" to an activity (Or how to terminate an activity)?

by Jun Sun » Tue, 20 May 2008 18:51:56 GMT

 Still no luck. See my reply below.

If by "back button" you mean the one on the right side with an arrow to the
left-top, it does not work to me. Press back button and nothing happened,

I tried them all, but it seems onCreate() is always called in each case.
Isn't that conflicting with all these modes? How do I which call
represents "bringing to front" so that I will know not to start the socket

Unfortunately it appears when the thread is doing accept(), it cannot
be interrupted. Is that true?

It appears the socket thread did not get killed even when I call super.finish().