I've been searching for this and only find really messed up things.
Isn't there a easy way to show the battery level like 21% on a toast or Textview?
Or how can i achieve this?
//Simon
To get the battery level right now, call:
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
(note: typing that in from memory, please adjust if needed)
This will return an Intent with various extras documented on the BatteryManager class. Use BatteryManager.EXTRA_LEVEL and BatteryManager.EXTRA_SCALE to determine the percentage remaining.
If you need to know over a period of time as the battery changes, use the BroadcastReceiver approach #Augusto outlined in his answer.
if you mean changing the battery status on the emulator do the following. Connect to the emulator via telnet and change the status and capacity
> telnet localhost 5554
Android Console: type 'help' for a list of commands
OK
power ac off
OK
power discharging
OK
power capacity 21
OK
exit
>
Ahh, well you can do what it says on the page Ted mentioned, and then use a handler to show a toast. This is the code you need to add to your activity.
private Handler handler = new Handler;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Log.i(TAG, "level: " + level + "; scale: " + scale);
int percent = (level*100)/scale;
final String text = String.valueOf(percent) + "%";
handler.post( new Runnable() {
public void run() {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
});
}
};
public static String batteryLevel(Context context)
{
Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level*100)/scale;
return String.valueOf(percent) + "%";
}
You can use this.
private void batteryLevel() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
batterLevel.setText("Battery Level Remaining: " + level + "%");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
I used a combination like that:
BatteryManager bm = (BatteryManager) getActivity().getSystemService(BATTERY_SERVICE);
int batLevel = 100;
int level;
int scale;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
}
if(batLevel == 0){
Intent intent = getActivity().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
batLevel = (level*100)/scale;
}
I did it like that because on a Nexus 5 device with Marshmallow "batLevel" returned 0 always. That solved it completely!
Good luck
Related
is this correct?
im modifying a source code from github : USB CHARGE COMMANDER
when battery goes down from 20 percent it will charge
when batter goes 80 it wont
and countdown timer is for it to do this every 5 mins
i set 20000 just for testing
boolean startcountdown=true;
do{
new CountDownTimer(20000, 1000) {
Intent intent = _context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level*100)/scale;
public void onTick(long millisUntilFinished) {}
public void onFinish() {
if(percent <= 20){
_iIsCharging = 1;
}
else if (percent >=80){
_iIsCharging = 0;
}
else{
_iIsCharging = 1;
}
}
}.start();
}while(startcountdown);
There is no way for this do/while loop to end, it's an infinite loop at the moment. The boolean "startcountdown" needs some way to eventually go to the value of FALSE. For example
if (_iIsCharging == 0) {
startcountdown = false;
}
I have register battery low broadcast receiver.
Like this
import com.save.sharedpreference.SharedPreference;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.widget.Toast;
public class BootReceiver extends BroadcastReceiver {
String user_phone_key = "phone_number";
int last_level = 0;
#Override
public void onReceive(Context context, Intent intent) {
int rlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
int level = -1;
if (rlevel >= 0 && scale > 0) {
level = (rlevel * 100) / scale;
}
if (level == 48 && last_level == level + 1) {
SharedPreference save_data = new SharedPreference(
context.getApplicationContext());
String phone = save_data.get_string(user_phone_key, null);
Toast.makeText(context, "Level Decrease", Toast.LENGTH_SHORT)
.show();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phone, null,
"Your Battery level is less ", null, null);
} catch (Exception e) {
Toast.makeText(context.getApplicationContext(),
"SMS faild, please try again later!", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}
}
last_level = level + 1;
}
}
Its working fine but the problem is when my battery level is reach 45% it start sending me sms until battery level change from 45%.
I want that when my battery level is reach 45% it just send me sms only one time and again waiting when battery level is 45%.
Is it possible?
Any help please.
Can you just use a local variable, like this?
public class BootReceiver extends BroadcastReceiver {
String user_phone_key = "phone_number";
int last_level = 0;
#Override
public void onReceive(Context context, Intent intent) {
int rlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
int level = -1;
if (rlevel >= 0 && scale > 0) {
level = (rlevel * 100) / scale;
}
if (level == 45 && last_level == 46) {
...
last_level = level;
}
}
I know it's not the most elegant solution, but it should work.
The more "official" solution is to use the ACTION_BATTERY_LOW intent to detect charge decreases, which IIRC only fires once, when the device hits low battery. Is there a reason you need to detect the battery level hitting 45%, in particular?
Create a boolean variable to send message only once.Like-
boolean isMsgSent=false;
and modify if loop as-
if(level==45 && !isMsgSent){
// send Msg
isMsgSent=true;
}
else{
isMsgSent=false;
}
It will send message only once when battery level is 45.
I found this code to create a battery widget:
public class BatteryStatusWidgetActivity extends AppWidgetProvider {
/** Called when the activity is first created. */
private String batteryLevel = "init";
private int widgetImageFrame = R.drawable.widget_batt_frame01;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
context.getApplicationContext().registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
updateView(context);
}
#Override
public void onReceive(Context context, Intent intent) {
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = 65;
level = (rawlevel * 100) / scale;
String batteryLevel = level + "%";
widgetImageFrame = R.drawable.widget_batt_frame01;
updateView(context);
super.onReceive(context, intent);
}
public void updateView(Context context) {
RemoteViews thisViews = new RemoteViews(context.getApplicationContext().getPackageName(), R.layout.widget_layout);
thisViews.setTextViewText(R.id.widget_text, batteryLevel);
thisViews.setImageViewResource(R.id.imageView1, widgetImageFrame);
ComponentName thisWidget = new ComponentName(context, BatteryStatusWidgetActivity.class);
AppWidgetManager.getInstance(context).updateAppWidget(thisWidget, thisViews);
}
This will display in the widget only the number of battery level. I mean "65" and i want display "65%". But if i try to write something like batteryLevel = Integer.toString(level+"%"); i get error.. How can i do it?
int level = 65;
String batteryLevel = level + "%";
Try this it will work
int level= 65;
String batterylevel = String.valueOf(level)+"%";
just replace your code in onReceive() to the following,
#Override
public void onReceive(Context context, Intent intent) {
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
level = (rawlevel * 100) / scale;
batteryLevel = level+"%";
widgetImageFrame = R.drawable.widget_batt_frame01;
updateView(context);
super.onReceive(context, intent);
}
The basic reason you get an error for Integer.toString(level+"%") is Integer.toString() method used here accepts an int value but not a String value. level+"%" is a String value
Change it to this:
int level = -1
level = (rawlevel * 100) / scale;
String batteryLevel = level + "%";
I want more information about android.permission.BATTERY_STATS . what possibilities grants the permission android.permission.BATTERY_STATS. I know how to use it if I can read the android.intent.action.BATTERY_CHANGED intent for the battery levels without declare such permission.
use this code that will get you the amount of battery used, the battery voltage, and its temperature.
#Override
public void onCreate() {
BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
int scale = -1;
int level = -1;
int voltage = -1;
int temp = -1;
#Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
Log.e("BatteryManager", "level is "+level+"/"+scale+", temp is "+temp+", voltage is "+voltage);
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, filter);
}
Is there a way to get battery information from the Android SDK? Such as battery life remaining and so on? I cannot find it through the docs.
Here is a quick example that will get you the amount of battery used, the battery voltage, and its temperature.
Paste the following code into an activity:
#Override
public void onCreate() {
BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
int scale = -1;
int level = -1;
int voltage = -1;
int temp = -1;
#Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
Log.e("BatteryManager", "level is "+level+"/"+scale+", temp is "+temp+", voltage is "+voltage);
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, filter);
}
On my phone, this has the following output every 10 seconds:
ERROR/BatteryManager(795): level is 40/100 temp is 320, voltage is 3848
So this means that the battery is 40% full, has a temperature of 32.0 degrees celsius, and has voltage of 3.848 Volts.
You can register an Intent receiver to receive the broadcast for ACTION_BATTERY_CHANGED: http://developer.android.com/reference/android/content/Intent.html#ACTION_BATTERY_CHANGED. The docs say that the broadcast is sticky, so you'll be able to grab it even after the moment the battery state change occurs.
public static String batteryLevel(Context context)
{
Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level*100)/scale;
return String.valueOf(percent) + "%";
}
I needed to have a monitor on the battery and check the Level and the status. I am developing on MonoForAndroid, so here is what I came up with. I am putting it here in case somebody have a similar requirement. (I have tested this and works nicely).
try
{
var ifilter = new IntentFilter(Intent.ActionBatteryChanged);
Intent batteryStatusIntent = Application.Context.RegisterReceiver(null, ifilter);
var batteryChangedArgs = new AndroidBatteryStateEventArgs(batteryStatusIntent);
_Battery.Level = batteryChangedArgs.Level;
_Battery.Status = batteryChangedArgs.BatteryStatus;
}
catch (Exception exception)
{
ExceptionHandler.HandleException(exception, "BatteryState.Update");
throw new BatteryUpdateException();
}
namespace Leopard.Mobile.Hal.Battery
{
public class AndroidBatteryStateEventArgs : EventArgs
{
public AndroidBatteryStateEventArgs(Intent intent)
{
Level = intent.GetIntExtra(BatteryManager.ExtraLevel, 0);
Scale = intent.GetIntExtra(BatteryManager.ExtraScale, -1);
var status = intent.GetIntExtra(BatteryManager.ExtraStatus, -1);
BatteryStatus = GetBatteryStatus(status);
}
public int Level { get; set; }
public int Scale { get; set; }
public BatteryStatus BatteryStatus { get; set; }
private BatteryStatus GetBatteryStatus(int status)
{
var result = BatteryStatus.Unknown;
if (Enum.IsDefined(typeof(BatteryStatus), status))
{
result = (BatteryStatus)status;
}
return result;
}
}
}
#region Internals
public class AndroidBattery
{
public AndroidBattery(int level, BatteryStatus status)
{
Level = level;
Status = status;
}
public int Level { get; set; }
public BatteryStatus Status { get; set; }
}
public class BatteryUpdateException : Exception
{
}
#endregion