Saturday, September 27, 2014

IntentService

IntentService allows execution of asynchronous Tasks on Separate Threads.

It is important to note that once your service has finished executing a task, it should be stopped as soon as possible so that it does not unnecessarily hold up valuable resources.

Unfortunately, a lot of developers often forgot to terminate a service when it is done performing its task.

It executes its task within a worker thread and terminates itself when the task is completed

    public void startService(View view)
    {
    startService(new Intent(getBaseContext(), MyIntentService.class));
    }

public class MyIntentService extends IntentService 
{

public MyIntentService(String name) {
super("MyIntentServiceName");
// TODO Auto-generated constructor stub
}

protected void onHandleIntent(Intent intent)
{
try
{
int result = downloadFile(new URL("http://www.amazon.com/somefile.pdf"));
}catch(MalformedURLException e)
{
e.printStackTrace();
}
}

private int downloadFile(URL url)
{
try
{
Thread.sleep(5000);
}catch(InterruptedException e)
{
e.printStackTrace();
}

return 100;
}
}    

No comments:

Post a Comment