Search Tutorials

Loading...

Monday, 11 November 2013

Display Battery Status using Broadcast Receiver in Android

This is simple example of Android Broadcast Receiver. In this android project, we will learn how to use broadcast receiver and how to get the battery level and display it on the progress bar. We used one text view to display battery status and one progress bar to display battery level in progress. Create a new project, Open an XML file and use text view and progress bar in a linear layout. The code of the Android XML file is given below:

Display Battery level using Broadcast Receiver in Android
Check Battery level using Broadcast Receiver

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical"
  android:background="#abc" >
<TextView
  android:id="@+id/textView1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text=""
  android:textSize="25sp"
  android:layout_gravity="center"
/>
<ProgressBar
  android:id="@+id/progressBar1"
  style="?android:attr/progressBarStyleHorizontal"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center"
  android:minHeight="100dp"
  android:minWidth="200dp" />
</LinearLayout>

Now open your Java file, initialize broadcast object and use broadcast class as a nested class. Here, we are registering a broadcast object with a battery changed intent filter which will receive updates on every level of the battery changed. Whenever the battery level changes, onReceive() method will be called, which will take two parameters. Use the code in onReceive() method to do whatever is required to be done on every level of battery change. We are setting a level on progress bar, displaying level on text view and whenever battery level becomes 100% then a song, stored in the assets folder, will start playing. The code of the Android Java file is given below with explanation:


package com.exampl.aaaa; //your package name
import java.io.IOException;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {
  //broadcast class is used as a nested class
  private BroadcastReceiver mbcr=new BroadcastReceiver()
  {
  //onReceive method will receive updates
  public void onReceive(Context c, Intent i)
  {
  //initially level has 0 value
  //after getting update from broadcast receiver
  //it will change and give battery status
  int level=i.getIntExtra("level", 0);
  //initialize all objects
  ProgressBar pb=(ProgressBar)findViewById(R.id.progressBar1);
  TextView tv=(TextView)findViewById(R.id.textView1);
  //set level of progress bar
  pb.setProgress(level);
  //display level on text view
  tv.setText("Batterylevel:"+Integer.toString(level)+"%");
  //start a song when the battery level touches 100%
  if(level==100)
  {
   try
   {
   //Save small.mp4 in assets folder
  //we can not start a media file from the drawable folder directly in broadcast method
   //hence we used the assets folder
   AssetFileDescriptor afd=getAssets().openFd("small.mp4");
   MediaPlayer mp=new MediaPlayer();
   //set file and starting point and ending point in bytes
   mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
   mp.prepare();
   //start song
   mp.start();
    }
    catch(IOException e){}
   }
  }
};
  /** Called when the activity is first created. */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   //set layout
   setContentView(R.layout.activity_main);
   //register broadcast receiver
   //Get battery changed status
   //we can get more options like power connect, disconnect, call, etc.
   //To get more options, write Intent followed by a dot(.) and press CTRL+Space
   //you will get all the options
   registerReceiver(mbcr,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  }
}
  

Now run your project and test application. If you have any doubts please comment. Share and help others.

Related Tutorials:-

Convert Text to Speech

Use Shared Preferences

Perform action on any Hardware button

Get all Mobile Contacts

Display Time using Broadcast Receiver

9 comments:

  1. brother can u explain about BroadcastReceiver in simple words..??

    ReplyDelete
    Replies
    1. If you want know system events like incoming call, incoming message, changing in time, changing battery status, etc. Than implements broadcast receiver and register it. We have given two example one for changing time and another for battery status changed. You can perform any action when any event occurs. Alarm application without alarm manager is based on broadcast receiver because it calls onRecieve() method when time completed of the alarm.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. sir i would like to give user an option to stop the song by unchecking switch button and the song to be played when switch button is checked and level is 100. can u guide me how to do so

    ReplyDelete
    Replies
    1. i have used this code but it has a bug as it dosen't stop the song
      please help me out


      final Switch swbat=(Switch)view.findViewById(R.id.switch2);

      alarm11=MediaPlayer.create(getActivity(), R.raw.akhiyan);



      if(swbat.isChecked() && level== 91 ){
      try{
      alarm11.start();
      }
      catch(Exception e){}

      }


      else{
      alarm11.stop();


      }

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Thank u so much.... i have been working on this... and finally it worked... am new in app development...

    ReplyDelete
  6. i want to pass to the bluetooth signal to cut off the supply when it is 100% can you help me plzzz??

    ReplyDelete
  7. hello this code hight battery tts speak low battery tts speak source code?

    ReplyDelete

Back to Top