Hello,
A background thread in the main activity is almost, but not quite the
same as an Android service.
Quoting from
http://developer.android.com/reference/android/app/Service.html:
The Android system will attempt to keep the process hosting a
service around as long as the service has been started or has
clients bound to it.
No such thing is attempted for plain background threads.
So your app can do the time consuming tasks inside service.onStart(),
passing data (for example) in the intent used to start the service.
However, Services execute on the main application thread. If a separate
thread is needed, it can be created by the service inside onStart().
There is already a built-in class that does this:
http://developer.android.com/reference/android/app/IntentService.html
-- Kostya
11.06.2010 13:23, NightGospel ?????:
Hi all,
Be one of Android developers, you must be aware of the
ANR(Application Not Responding) very well and understand how to avoid
it. There are many ways you can choose to do. I usually create a
thread and use a flag
to trigger it to handle time-consuming tasks. For example:
public class ActivityA extends Activity implements OnClickListener{
private boolean isDestroyed = false;
private FetchThread thread;
public void onCreate(Bundle b){
super.onCreate(b);
.
.
}
public void onDestroy(){
super.onDestroy();
isDestroyed = true;
}
public void onClick(View view){
thread = new FetchThread();
thread.setStartFlag(true);
thread.start();
}
class FetchThread extends Thread{
private boolean shouldStart = false;
public void run(){
while (!isDestroyed){
if (shouldStart){
shouldStart = false;;
// do time-consuming task
// after task is finished, use handler to update
UI
}
try{
sleep(500);
} catch (Exception ex){}
}
}
public void setStartFlag(boolean b) { shouldStart = b;}
}
}
The above is the way I usually do and it's as the same as running one
background service. Does anyone be able to provide your solution? I
think my method is not very smart. :(
NightGospel
--
Kostya Vasilev -- WiFi Manager + pretty widget -- http://kmansoft.wordpress.com
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en