Sunday, September 23, 2012

Create our own Service and BroadcastReceiver in Android

In this onStart() of the main activity(AndroidServiceTestActivity.java), we instance and register our own BroadcastReceiver(myReceiver), and also start our service(MyService.java). In MyService.java, It will send 10 actions with MY_ACTION. It will trigger the myReceiver in AndroidServiceTestActivity.java.





Main activity AndroidServiceTestActivity.java


package com.AndroidServiceTest;
 
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.widget.Toast;
 
public class AndroidServiceTestActivity extends Activity {
 
MyReceiver myReceiver;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
 
   }
 
@Override
protected void onStart() {
 // TODO Auto-generated method stub
 
       //Register BroadcastReceiver
       //to receive event from our service
       myReceiver = new MyReceiver();
       IntentFilter intentFilter = new IntentFilter();
       intentFilter.addAction(MyService.MY_ACTION);
       registerReceiver(myReceiver, intentFilter);
       
       //Start our own service
       Intent intent = new Intent(AndroidServiceTestActivity.this,
         com.AndroidServiceTest.MyService.class);
       startService(intent);
 
 super.onStart();
}
 
@Override
protected void onStop() {
 // TODO Auto-generated method stub
 unregisterReceiver(myReceiver);
 super.onStop();
}
 
private class MyReceiver extends BroadcastReceiver{
 
 @Override
 public void onReceive(Context arg0, Intent arg1) {
  // TODO Auto-generated method stub
  Toast.makeText(AndroidServiceTestActivity.this,
    "Triggered by Service!",
    Toast.LENGTH_LONG).show();
  
 }
 
}
}


MyService.java

package com.AndroidServiceTest;
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
 
public class MyService extends Service {
 
final static String MY_ACTION = "MY_ACTION";
 
@Override
public IBinder onBind(Intent arg0) {
 // TODO Auto-generated method stub
 return null;
}
 
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
 // TODO Auto-generated method stub
 
 MyThread myThread = new MyThread();
 myThread.start();
 
 return super.onStartCommand(intent, flags, startId);
}
 
public class MyThread extends Thread{
 
 @Override
 public void run() {
  // TODO Auto-generated method stub
  for(int i=0; i<10; i++){
   try {
    Thread.sleep(5000);
    Intent intent = new Intent();
       intent.setAction(MY_ACTION);
       sendBroadcast(intent);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  stopSelf();
 }
 
}
 
}