Sunday, April 17, 2011

Android IntentService, how to write a background service keep polling data and notify Activity for Change.

Let me put a simple test application, One activity and One Service. for the service, it will do the background job like networking, computation. and notify the Acidity to do some UI side rendering or notification to User.

first , Create one Simple Android application with just one Activity,

public class UIActivity extends Activity {
    /** Called when the activity is first created. */
   
    TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv=new TextView(this);
        tv.setText("hello,World");
        setContentView(tv);
    }
   
   
}


then Add one Handler in the activity which will be called by the bakcground service when there are any change get triggered,

Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            //get data from msg
           
            String result=msg.getData().getString("result");
            tv.setText(result);
            Log.d("xxxxx", "get data" + result);
            super.handleMessage(msg);
        }
    };


then Create one Service inherited from IntentService, here we defined a timer which will do the periodic checking and send back data change to activity,

public class BackService extends IntentService {

    public BackService()
    {
        super("myintentservice");
    }
   
   
    Messenger messenger;
    Timer t=new Timer();
   
   
    @Override
    protected void onHandleIntent(Intent intent) {
        messenger=(Messenger) intent.getExtras().get("handler");
       
        t.schedule(new TimerTask() {
           
            @Override
            public void run() {
                // just call the handler every 3 Seconds
               
                Message msg=Message.obtain();
                Bundle data=new Bundle();
                data.putString("k", "value" + System.currentTimeMillis() );
                msg.setData(data);
               
                try {
                    messenger.send(msg);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }, 100,3000);
       
    }

}


for Activity, need to specify the handler through putextra and start the service,

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     tv=new TextView(this);
     tv.setText("hello,World");
     setContentView(tv);
    
     Intent i=new Intent(this, BackService.class);
     i.putExtra("handler", new Messenger(this.handler));
     this.startService(i);
    
}


remember to register the backservice into the manifest.xml,
when you run the app, you will see the textview will change every 3 seconds,
image
run adb logcat XXXXX:D *:S, even the activity is brought to background , the Activity still get the change from service,
image

2 comments:

Austin H said...

Is passing a Handler really the best way to handle passing messages from the IntentService to the calling Activity? If the activity is paused/killed the Handler is going to get destroyed as well... Broadcast intents would probably be the best solution.

F.T said...

yes a friend of me faced the same sort of problem, but now this app solved.

Jaycon

Arduino

 
Locations of visitors to this page