Executing Asynchronous tasks on Separate threads using intentService
In earlier posts, you saw how to start a service using the startService() method and stop a service using the stopService() method.
You have also seen how you should execute long-running task on a separate thread — not the same thread as the calling activities.
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.
That’s why you use the stopSelf() method to stop the service when a task has been completed. Unfortunately, a lot of developers often forgot to terminate the service when it is done performing its task.
To easily create a service that runs a task asynchronously and terminates itself when it is done, you can use the IntentService class.
The IntentService class is a base class for Service that handles asynchronous requests on demand.
It is started just like a normal service and it executes its task within a worker thread and terminates itself when the task is completed.
The following example demonstrates how to use the IntentService class.
Using the intentService Class to Auto-Stop a Service
1. Add a new class file named MyIntentService.java.
2 . Populate the MyIntentService.java file as follows:
package com.emergingandroidtech.Services;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentServiceName");
}
@Override
protected void onHandleIntent(Intent intent) {
try {
int result =
DownloadFile(new URL("http://www.amazon.com/somefile.pdf"));
Log.d("IntentService", "Downloaded " + result + " bytes");
//---send a broadcast to inform the activity
// that the file has been downloaded---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
getBaseContext().sendBroadcast(broadcastIntent);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private int DownloadFile(URL url) {
try {
//---simulate taking some time to download a file---
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 100;
}
}
3 . Add the following statement in bold to the AndroidManifest.xml file:
<?xml version="1.0"
encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.emergingandroidtech.Services"
android:versionCode="1"
android:versionName="1.0">
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
<service
android:name=".MyService">
<intent-filter>
<action android:name="com.emergingandroidtech.MyService"
/>
</intent-filter>
</service>
<service
android:name=".MyIntentService" />
</application>
<uses-sdk
android:minSdkVersion="9" />
<uses-permission
android:name="android.permission.INTERNET"></uses-permission>
</manifest>
4. Add the following in main.xml file.
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="@+id/btnStartService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start Service" />
<Button android:id="@+id/btnStopService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop Service" />
</LinearLayout>
5 . Add the following statement in bold to the MainActivity.java file:
public class MainActivity extends Activity
{
/**Called when the activity is first created.*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStart=(Button)findViewById(R.id.btnStartService);
btnStart.setOnClickListener(newView.OnClickListener()
{
public void onClick(View v)
{
//startService(new Intent(getBaseContext(), MyService.class));
startService(new Intent(getBaseContext(), MyIntentService.class));
}
});
Button btnStop=(Button)findViewById(R.id.btnStopService);
btnStop.setOnClickListener(newView.OnClickListener()
{
public void onClick(View v)
{
stopService(newIntent(getBaseContext(),MyService.class));
}
});
}
}
5 . Click the Start Service button. After about five seconds, you should observe the following statement in the LogCat window:
01-1703:05:21.244:DEBUG/IntentService(692): Downloaded 100bytes
No comments:
Post a Comment