[ACCEPTED]-How to start service in new thread in android-android
To create and start a new thread, from inside 3 an activity, you can say:
Thread t = new Thread(){
public void run(){
getApplicationContext().bindService(
new Intent(getApplicationContext(), MyAndroidUpnpServiceImpl.class),
serviceConnection,
Context.BIND_AUTO_CREATE
);
}
};
t.start();
Also, cache the 2 value returned by bindservice, if any, if 1 you require it for later use.
Any solution which uses Threads, Runnables, AsyncTask 7 or otherwise with a Service will have a 6 common problem.
The Service will block the calling Activity until after the service is started. And thus doesn't effectively thread the 5 Service in certain cases.
The solution to 4 this is to use the IntentService subclass.
Example of 3 how to implement:
public class MyCustomService extends IntentService
{
private DatabaseAdapter mAdapter;
public MyCustomService() {
super("MyCustomService");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "MyCustomService Started", Toast.LENGTH_LONG).show();
// Don't let this service restart automatically if it has been stopped by the OS.
return START_NOT_STICKY;
}
@Override
protected void onHandleIntent(Intent intent)
{
Toast.makeText(this, "MyCustomService Handling Intent", Toast.LENGTH_LONG).show();
// INSERT THE WORK TO BE DONE HERE
}
}
onCreate() and onDestroy 2 can also be overriden so long as super.onWhatever()
is called 1 inside them.
Old question, but I'm responding because 14 someone drew my attention to it in another 13 question.
The OP's problem was evidently 12 caused by the service's onBind(...)
taking a long time 11 and blocking the main thread. The correct 10 solution is don't do that. The service needs to be redesigned 9 so that onBind(...)
returns quickly. Like almost everything 8 else in the Android API, you should always 7 call bindService(...)
in the main thread.
The reason is that 6 thread safety in Java is not just a matter 5 of atomicity, but also visibility. (Scroll down to 4 the visibility section.) In general, you 3 should always assume that every Java API 2 is not thread safe unless it's explicitly documented 1 otherwise.
I would recommend using an IntentService, because 3 an IntentService by default runs on a separate 2 thread. But still if your service class 1 extends Service then use this code:
Thread thread = new Thread() {
@Override
public void run() {
startService(new Intent(getApplicationContext(), YourService.class));
}
};
thread.start();
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.