How to Create Global Broadcast Receiver and Test Service in Android

Introduction

 
This article explains how to create a global broadcast receiver as well as to create services in an Android project. First of all, we will create a new project in Android.
 
Procedure
  1. Start the Eclipse IDE.
  2. Create a new project.
  3. Create a MainActivity.java (here Abhijeet.java) file.
  4. Create a new java file bootstartup.java as in the following:
    1. public class bootstartup extends BroadcastReceiver {    
    2.         
    3.     @Override    
    4.      
    5.     public void onReceive(Context context, Intent intent) {    
    6.         
    7.     // start the service    
    8.     Intent service=new Intent(context,TestService.class);    
    9.     context.startService(service);    
    10. Log.e("com.example.myglobalbroadcastreceiver",    
    11. "BroadcastReceived:"+intent.getAction())    
    12.         
    13.     // start the app    
    14. Intent app= new Intent(context,Abhijeet.class);    
    15. context.startService(app);    
    1. Create a new java file TestService.java as in the following:
      1. public class TestService extends Service {    
      2.      
      3.             @Override    
      4.             public IBinder onBind(Intent arg0) {    
      5.                         // TODO Auto-generated method stub    
      6.             throw new UnsupportedOperationException("it is not implemented");    
      7.             }    
      8.      
      9.             @Override    
      10.             public void onCreate() {    
      11.                         // TODO Auto-generated method stub    
      12.                         super.onCreate();    
      13. Toast.makeText(getApplicationContext(), "abhijeet's Service is created",1).show();    
      14.                            
      15.             }    
      16.      
      17.             @Override    
      18.             public void onDestroy() {    
      19.                         // TODO Auto-generated method stub    
      20.      
      21. Toast.makeText(getApplicationContext(), "Service is destroyed",1).show();    
      22.                            
      23.                         super.onDestroy();    
      24.             }    
      25.      
      26.             @Override    
      27.             public int onStartCommand(Intent intent, int flags, int startId) {    
      28.                         // TODO Auto-generated method stub    
      29.      
      30. Toast.makeText(getApplicationContext(), " abhijeet's Service is working",1).show();    
      31.                            
      32. return super.onStartCommand(intent, flags, startId);    
      33.             }    
      1. Now add a bootstartup.java file as a receiver.
         
        Step 1: Open the application of the manifest file as in the following:
         
        Manifest File
         
        Step 2: Then click on Add for adding a receiver.
         
        Adding Reciever
         
        Step 3: It will automatically search the bootstartup receiver class.
         
        Reciever Class
         
        Step 4: It is very important for making a global receiver that we should provide a name to that receiver such that the name is started with a dot followed by a lower-case letter.
         
        Global Reciever
         
        Step 5: Set the Exported and Enabled properties to true as in the following:
         
        Enabling Property
         
        Step 6: Add actions on the receiver in the manifest file as in the following:
         
        Adding Actions
         
      2. Now add a TestService.java file as a Service in the manifest file.
         
        Step 1: Select Service.
         
        Select Service
         
        Step 2: It will automatically search the TestService class.
         
        Adding Class
         
        Step 3: Select the true option for the exported and enabled properties as in the following:
        1. <service android:name="TestService" android:exported="true" android:enabled="true" android:permission="android.permission.INTERNET"></service>  
      Code- Abhijeet.java 
      1. package com.example.myglobalbroadcastreceiver;    
      2. import android.support.v7.app.ActionBarActivity;    
      3. import android.support.v7.app.ActionBar;    
      4. import android.support.v4.app.Fragment;    
      5. import android.os.Bundle;    
      6. import android.view.LayoutInflater;    
      7. import android.view.Menu;    
      8. import android.view.MenuItem;    
      9. import android.view.View;    
      10. import android.view.ViewGroup;    
      11. import android.os.Build;    
      12.     
      13. public class Abhijeet extends ActionBarActivity {    
      14.     
      15.             @Override    
      16.             protected void onCreate(Bundle savedInstanceState) {    
      17.                         super.onCreate(savedInstanceState);    
      18.                         setContentView(R.layout.activity_abhijeet);    
      19.      
      20.                         if (savedInstanceState == null) {    
      21.                                     getSupportFragmentManager().beginTransaction()    
      22.                                                             .add(R.id.container, new PlaceholderFragment()).commit();    
      23.                         }    
      24.             }     
      25.     
      26.             @Override    
      27.             public boolean onCreateOptionsMenu(Menu menu) {    
      28.      
      29.                         // Inflate the menu; this adds items to the action bar if it is present.    
      30.                         getMenuInflater().inflate(R.menu.abhijeet, menu);    
      31.                         return true;    
      32.             }    
      33.      
      34.             @Override    
      35.             public boolean onOptionsItemSelected(MenuItem item) {    
      36.                         // Handle action bar item clicks here. The action bar will    
      37.                         // automatically handle clicks on the Home/Up button, so long    
      38.                         // as you specify a parent activity in AndroidManifest.xml.    
      39.                         int id = item.getItemId();    
      40.                         if (id == R.id.action_settings) {    
      41.                                     return true;    
      42.                         }    
      43.                         return super.onOptionsItemSelected(item);    
      44.             }    
      45.      
      46.             /**  
      47.              * A placeholder fragment containing a simple view.  
      48.              */    
      49.             public static class PlaceholderFragment extends Fragment {    
      50.      
      51.                         public PlaceholderFragment() {    
      52.                         }     
      53.                         @Override    
      54.                         public View onCreateView(LayoutInflater inflater, ViewGroup container,    
      55.                                                 Bundle savedInstanceState) {    
      56.                                     View rootView = inflater.inflate(R.layout.fragment_abhijeet,    
      57.                                                             container, false);    
      58.                                     return rootView;    
      59.                         }    
      60.             }     
      61. }   
        bootstartup.java
        1. package com.example.myglobalbroadcastreceiver;    
        2. import android.content.BroadcastReceiver;    
        3. import android.content.Context;    
        4. import android.content.Intent;    
        5. import android.util.Log;    
        6.      
        7. public class bootstartup extends BroadcastReceiver {    
        8.      
        9.             @Override    
        10.                
        11.             public void onReceive(Context context, Intent intent) {    
        12.                         // TODO Auto-generated method stub    
        13.                         // start the service    
        14.                         Intent service=new Intent(context,TestService.class);                        
        15.                         context.startService(service);                      
        16.                         Log.e("com.example.myglobalbroadcastreceiver","Broadcast Received:"+intent.getAction());                           
        17.                
        18.                         // start the app                 
        19.                         Intent app= new Intent(context,Abhijeet.class);    
        20.                         context.startService(app);               
        21.             }    
        22. }    
          TestService.java
          1. package com.example.myglobalbroadcastreceiver;    
          2. import android.app.Service;    
          3. import android.content.Intent;    
          4. import android.os.IBinder;    
          5. import android.widget.Toast;    
          6.      
          7. public class TestService extends Service {    
          8.      
          9.             @Override    
          10.             public IBinder onBind(Intent arg0) {    
          11.                         // TODO Auto-generated method stub    
          12.                         throw new UnsupportedOperationException("it is not implemented");    
          13.             }    
          14.      
          15.             @Override    
          16.             public void onCreate() {    
          17.                         // TODO Auto-generated method stub    
          18.                         super.onCreate();                          
          19.                         Toast.makeText(getApplicationContext(), "abhijeet's Service is created",1).show();       
          20.             }    
          21.      
          22.             @Override    
          23.             public void onDestroy() {    
          24.                         // TODO Auto-generated method stub                   
          25.                         Toast.makeText(getApplicationContext(), "Service is destroyed",1).show();                  
          26.                         super.onDestroy();    
          27.             }    
          28.      
          29.             @Override    
          30.             public int onStartCommand(Intent intent, int flags, int startId) {    
          31.                         // TODO Auto-generated method stub                   
          32.                         Toast.makeText(getApplicationContext(), " abhijeet's Service is working",1).show();    
          33.                         return super.onStartCommand(intent, flags, startId);    
          34.             }    
          35. }    
            Output
             
            Step 1: Run the Application.
             
            Running Application on Android
             
            Step 2: Click on the back button.
             
            Clicking on Back Button
             
            Step 3: Go to Settings.
             
            Settings on Android App
             
            Step 4: Go to Data Usage and turn on the mobile data. We can see that the service is working. It is due to the action used in the receiver.
             
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"   /> 
             
            Data Usage of Android App


            Similar Articles