BroadcastReceiver to get Battery Level - simple Example using dynamic calling of BroadCast in ANDROID
See Introduction for Broadcast Receiver here:
When you need to call a broadcast (suppose here battery value) you need to register the broadcast and when the event is published it will call onReceive method which have context and particular intent as parameter.
receiver :: The BroadcastReceiver you want to register
filter :: The IntentFilter object that specifies which event your receiver should listen to.
To learn more on event and usages click here...
When you need to call a broadcast (suppose here battery value) you need to register the broadcast and when the event is published it will call onReceive method which have context and particular intent as parameter.
public class Broadcast extends Activity { //Create broadcast object BroadcastReceiver mybroadcast = new BroadcastReceiver() { //When Event is published, onReceive method is called @Override public void onReceive(Context context, Intent intent) { //Get battery percentage int batterylevel = intent.getIntExtra("level", 0); //get progressbar ProgressBar myprogressbar = (ProgressBar) findViewById(R.id.progressbar); myprogressbar.setProgress(batterylevel); TextView tv = (TextView) findViewById(R.id.textfield); //Set TextView with text tv.setText("Battery Level: " + Integer.toString(batterylevel) + "%"); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_broadcast); registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); } }The arguments of the registerReceiver() method
receiver :: The BroadcastReceiver you want to register
filter :: The IntentFilter object that specifies which event your receiver should listen to.
To learn more on event and usages click here...
Nice post Angel.. Thanks for sharing this. Even this http://www.compiletimeerror.com/2013/05/android-battery-percentage-example.html might help.. have a look...
ReplyDeleteya...that too is nice one ...thanks for your reference Meghna
Deletecan u plzz give the layout.xml for this.. im just a starter in this
ReplyDeletethanks