Topic Broadcast Receivers Please provide android studio code
Topic: Broadcast Receivers
Please provide android studio code i.e java and xml code for the activity below:
Create an Android project
Create a broadcast receiver class, which listens to battery intents
i.e. Intent.ACTION_BATTERY_CHANGED
In your activity, create a new instance of your receiver class, and register it to listen to events programmatically
In your broadcast receiver class, when a broadcast intent is received, display an appropriate message using a Notification. The notification should display:
o Whether the battery is charging, discharging, or full
This is stored in the intent with the name BatteryManager.EXTRA_STATUS
For possible values, check out the BatteryManager class
o Whether or not the battery is healthy (BATTERY_HEALTH_GOOD)
Otherwise, display a message about what is wrong with the battery
o Whether or not the battery is plugged in
If so, display whether it is plugged into a USB port or an AC outlet
o The current temperature of the battery
Solution
package com.chegg.android;
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.widget.ProgressBar;
import android.widget.TextView;
public class BatteryIndicatorActivity extends Activity {
//Create Broadcast Receiver Object along with class definition
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
@Override
//When Event is published, onReceive method is called
public void onReceive(Context c, Intent i) {
//Get Battery %
int level = i.getIntExtra(\"level\", 0);
//Find the progressbar creating in main.xml
ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
//Set progress level with battery % value
pb.setProgress(level);
//Find textview control created in main.xml
TextView tv = (TextView) findViewById(R.id.textfield);
//Set TextView with text
tv.setText(\"Battery Level: \" + Integer.toString(level) + \"%\");
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set layout we created
setContentView(R.layout.main);
//Register the receiver which triggers event
//when battery charge is changed
registerReceiver(mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
}
}

