How to start service in new thread in android

I'm new to this android. i'm using a service to do some background work. so i'm starting the service from my activity as following.

        getApplicationContext().bindService(
        new Intent(getApplicationContext(), MyAndroidUpnpServiceImpl.class),
        serviceConnection,
        Context.BIND_AUTO_CREATE
    );

but the problem is android activity is blocked. untill the service,

         onServiceConnected(ComponentName className, IBinder service){ ..}

is called back.so i searched regarding this. i came to know that i have to start my service in new Thread. so please any one help me in doing this.

Answers


To create and start a new thread, from inside 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 value returned by bindservice, if any, if you require it for later use.


Any solution which uses Threads, Runnables, AsyncTask or otherwise with a Service will have a common problem.

The Service will block the calling Activity until after the service is started. And thus doesn't effectively thread the Service in certain cases.

The solution to this is to use the IntentService subclass.

Example of 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 can also be overriden so long as super.onWhatever() is called inside them.


Old question, but I'm responding because someone drew my attention to it in another question.

The OP's problem was evidently caused by the service's onBind(...) taking a long time and blocking the main thread. The correct solution is don't do that. The service needs to be redesigned so that onBind(...) returns quickly. Like almost everything else in the Android API, you should always call bindService(...) in the main thread.

The reason is that thread safety in Java is not just a matter of atomicity, but also visibility. (Scroll down to the visibility section.) In general, you should always assume that every Java API is not thread safe unless it's explicitly documented otherwise.


if anyone reading this is looking for a solution involving keeping the UI thread in a fluent run, you better check out the AsyncTask task here. cheers.


I would recommend using an IntentService, because an IntentService by default runs on a separate thread. But still if your service class extends Service then use this code:

Thread thread = new Thread() {
    @Override
    public void run() {
        startService(new Intent(getApplicationContext(), YourService.class));
    }
};
thread.start();

Need Your Help

What versions of .NET are supported on Azure Web Sites?

azure azure-web-sites

To avoid more questions like Azure Websites, Can one deploy .NET 4.5.1 websites? and Azure Websites, Can one deploy .NET 4.5.2 websites, is there a web site that lists all the .NET Frameworks that ...

How to open a mobile device's map app when a user clicks on a link?

html mobile

I have a web app where if a user clicks on a link it should open up a map. The best solution that I can think of is to open up a new tab/window to google maps using the target="_blank" attribute.