1

I wrote a J2ME Application in which i instantiated and started the Thread in MIDlet constructor.
[The thread needs to be started when the Midlet is launched and will continue to run throughout the lifecycle of MIDlet]

Now I have decided to port that app to android platform. And written an Activity class.

Now in Android which place is best to instantiate this thread?

1) Constructor in Android is not the way

2) OnCreate() gets called multiple times. like when screen orientation changes etc.

3) Cannot declare it on an event

gnat
  • 6,213
  • 108
  • 53
  • 73
krisp
  • 4,727
  • 5
  • 25
  • 26
  • What do you mean by **...started when the app is launched...**? Be aware that the generic term 'app', the Android `Application` class and the Android `Activity` class are not synonymous. If you can explain a little further as to what the thread will do and whether it needs only to run when the user has an `Activity` visible etc it may help get an answer. – Squonk May 20 '12 at 18:30
  • Edited my question to make it more clear.By "App is launched" i meant what is happening in the Midlet. Functionality in thread is to do some calculations. Looks like i need to make use of AsyncTask. – krisp May 21 '12 at 01:24
  • http://stackoverflow.com/questions/8839736/oncreate-method-keeps-getting-called-when-the-orientation-of-device-changes Looks like My problem is similar to this. – krisp May 21 '12 at 05:08
  • http://stackoverflow.com/questions/456211/activity-restart-on-rotation-android – krisp May 21 '12 at 05:34

1 Answers1

0

Depends what you need to do in your Thread.

You could instantiate it in onCreate() of the first Activity and then store it in a static (class) variable. Then, if your Activity is destroyed and recreated due to an orientation change, in onCreate() you can just check if that variable still points to an active Thread and either instantiate it or not as needed.

Another choice would be to return the reference to the Thread when the OS calls onRetainNonConfigurationInstance() before it destroys your activity (if it is going to recreate it due to an orientation change). Once the OS recreates your Activity, in onCreate() you can call getLastNonConfigurationInstance() to recover the Thread. This is an easy way to pass long-lived objects (like Threads, Connections, etc.) between instances of an Activity when the OS destroys and recreates them.

Note The nonConfigurationInstance stuff is deprecated in 4.0 and you can use Fragments to do the same thing.

David Wasser
  • 93,459
  • 16
  • 209
  • 274