Saturday, June 2, 2012

IntentService : Android


IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread - they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

IntentService is a subclass of Service, and can handle asynchronous requests (with Intent). Service can be started when needed, and a separate thread to handle each Intent to, but after processing will be canceled.

The work queue processor is generally used for the task from the application's main thread. All requests will be handled in a separate thread, but not blocking the main thread of the application. And time to process a request.

Service vs IntentService:

  • Service class uses the application’s main thread, while IntentService creates a worker thread and uses that thread to run the service.
  • IntentService creates a queue that passes one intent at a time to onHandleIntent(). Thus, implementing a multi-thread should be made by extending Service class directly.
  • Service class needs a manual stop using stopSelf(). Meanwhile, IntentService automatically stops itself when there is no intent in queue.
  • IntentService implements onBind() that returns null. This means that the IntentService can not be bound by default.
  • IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().

Service vs Thread vs AsyncTask:

  • Threads or Async task perform their tasks in a background thread thus they do not block the main thread, while a service performs it’s work in the main thread. so if a service is performing an intensive task such as calling a web service, it may block the main thread until it finishes. So for intensive tasks a service should run it’s work in a background thread.
  • A service runs in the same process of the application and keeps running until stopped by itself, stopped by the user or killed by the system if it needs memory.

IntentService of example:
   In IntentServiceActivity.java: :


package com.imrankhanandroid.Intentserviceexp; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class IntentServiceActivity extends Activity { private TextView text; private Button btnStart; private Button btnSendOther; private MessageReceiver receiver ; // Action private static final String ACTION_RECV_MSG = "com.imrankhanandroid.intent.action.RECEIVE_MESSAGE"; private static final String ACTION_OTHER_MSG = "com.imrankhanandroid.intent.action.OTHER_MESSAGE"; // Message private static final String MESSAGE_IN="message_input"; private static final String MESSAGE_OUT="message_output"; // Called when the activity is first created. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text=(TextView)findViewById(R.id.text); text.setText("Preparation"); btnStart=(Button)findViewById(R.id.btnStart); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent msgIntent = new Intent(IntentServiceActivity.this, IntentServicetest.class); text.setText(""); msgIntent.putExtra(MESSAGE_IN, text.getText().toString()); startService(msgIntent); } }); btnSendOther=(Button)findViewById(R.id.btnSendOther); btnSendOther.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); //Dynamic registration Receiver IntentFilter filter = new IntentFilter(ACTION_RECV_MSG); filter.addCategory(Intent.CATEGORY_DEFAULT); receiver = new MessageReceiver(); registerReceiver(receiver, filter); IntentFilter filter2 = new IntentFilter(ACTION_OTHER_MSG); filter2.addCategory(Intent.CATEGORY_DEFAULT); receiver = new MessageReceiver(); registerReceiver(receiver, filter2); } //Broadcast to receive public class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String message = intent.getStringExtra(MESSAGE_OUT); text.setText(message); Toast.makeText(context, "message",Toast.LENGTH_SHORT).show(); } } }

   In IntentServicetest.java: :



package com.imrankhanandroid.Intentserviceexp; import android.app.IntentService; import android.content.Intent; import android.os.SystemClock; import android.text.format.DateFormat; import android.util.Log; // IntentService public class IntentServicetest extends IntentService { // Action private static final String ACTION_RECV_MSG = "com.imrankhanandroid.intent.action.RECEIVE_MESSAGE"; // Message private static final String MESSAGE_IN="message_input"; private static final String MESSAGE_OUT="message_output"; private final static String Tag="---IntentServicetest"; public IntentServicetest() { // TODO Auto-generated constructor stub super("IntentServicetest"); Log.d(Tag, "Constructor"); } @Override public void onDestroy() { Log.d(Tag, "onDestroy()"); super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { Log.d(Tag, "onStart()"); super.onStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(Tag, "onStartCommand()"); return super.onStartCommand(intent, flags, startId); } @Override public void setIntentRedelivery(boolean enabled) { Log.d(Tag, "setIntentRedelivery()"); super.setIntentRedelivery(enabled); } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub Log.d(Tag, "IntentServicetest is onHandleIntent!"); String msgRecv = intent.getStringExtra(MESSAGE_IN); Log.d(Tag, msgRecv); for (int i = 0; i < 5; i++) { String resultTxt = msgRecv + " " + DateFormat.format("MM/dd/yy hh:mm:ss", System.currentTimeMillis()); Intent broadcastIntent = new Intent(); broadcastIntent.setAction(ACTION_RECV_MSG); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra(MESSAGE_OUT, resultTxt); sendBroadcast(broadcastIntent); SystemClock.sleep(1000); } } }

   In AndroidManifest.xml: :



<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.imrankhanandroid.Intentserviceexp" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="7" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".IntentServiceActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".IntentServicetest"></service> </application> </manifest>




   In main.xml: :



<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="30sp" android:textColor="#FF0000" android:text="@string/hello" /> <Button android:id="@+id/btnStart" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Start" /> <Button android:id="@+id/btnSendOther" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="SendOtherBroadcast" /> </LinearLayout>
Download Source Code: IntentServiceExample








0 comments:

Post a Comment

 
Powered by Blogger