Flashlight Part II (BatteryStats and Notifications)

FlashLight Part II

(Battery Stats and Notifications)

Picking up from where we left from  Part I, we are going to add some pretty cool design elements to the UI. It's quite simplistic and just shows the battery stats to the user so as to notify him/her about the battery percentage and temperature etc. Also we implement Notifications for the app so it can notify the user about whether the light is on or off. So let's begin with designing part first.

1. Add three TextViews to the layout from PartI

  • Drag and drop three text views in the Graphical Layout of the app (activity_main.xml).
  • Edit the xml as shown below.

App layout

2. Changes to the Manifest file

  • In the Manifest file of the previous part we make our activity launchMode as singleTask. This is required as we are going to implement the same activity as the Pending Intent to our Notification.
  • In the activity tag of the manifest file add the line -  android:launchMode="singleTask".

3. Display a Notification

  • To display a notification when the on button is pressed use the following function in the OnClickListner of the button.
  • The function uses the NotificationCompat.Builder class to create a notification.
  • The Pending Intent class is used to create a link to the same class (MainActivity)  when the notification is clicked on.
  • Finally the number_notifications variable is used to count the number of notification are there.

4. Cancel a Notification or all of them

5. Create a Broadcast Receiver for battery stats

6. MainActivity.java file 

Download Code


Shobhit Chittora

Hi there, I am Shobhit Chittora. I am a college student and like to develop apps for Android platform.I started this blog to share my experiences with Android development and may be help you guys on the “roadtodroid”.

  • Image
  • Image