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 + "%";
Related
I can't update the widget when is in charging state. The battery level stay the same. What is wrong in my code?
public class BatteryStatusWidgetActivity extends AppWidgetProvider {
/** Called when the activity is first created. */
private String batteryLevel = "init";
private String temperatura = "init";
private int widgetImageFrame = R.drawable.full;
#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) {
if (intent.getAction().contentEquals(
"com.sec.android.widgetapp.APPWIDGET_RESIZE")
|| intent.getAction().equals(
"android.appwidget.action.APPWIDGET_UPDATE_OPTIONS")) {
} else {
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 + "%";
// temperatura
int temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,
-1) / 10;
temperatura = temperature + "°C";
widgetImageFrame = R.drawable.full;
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 + " | "
+ temperatura);
thisViews.setImageViewResource(R.id.imageView1, widgetImageFrame);
ComponentName thisWidget = new ComponentName(context,
BatteryStatusWidgetActivity.class);
AppWidgetManager.getInstance(context).updateAppWidget(thisWidget,
thisViews);
}
}
This is the main of widget
<?xml version="1.0" encoding="utf-8" ?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:initialLayout="#layout/widget_layout" android:minWidth="40dp" android:minHeight="40dp" android:updatePeriodMillis="3000" />
So what is the problem? android:updatePeriodMillis="3000"?
The updatePeriodMillis attribute defines how often the App Widget framework should request an update from the AppWidgetProvider by calling the onUpdate() callback method.
from http://developer.android.com/guide/topics/appwidgets/index.html#MetaData
I'm making a widget and i know some of my code such as the broadcastReceiver is wrong at the moment but it wont even update to hardcoded setTextViewText.
My problem is I've no idea why this happens and my widget just wont update.
Here's my code i hope someone can figure out where ive gone wrong:
public class Widget extends AppWidgetProvider {
RemoteViews views;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
int N = appWidgetIds.length;
views = new RemoteViews(context.getPackageName(), R.layout.widget);
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
IntentFilter batteryLevelFliter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
context.registerReceiver(batteryChangedReceiver, batteryLevelFliter);
String alarm = Settings.System.getString(context.getContentResolver(),
Settings.System.NEXT_ALARM_FORMATTED);
views.setTextViewText(R.id.tvAlarm, alarm);
views.setTextViewText(R.id.tvNextAlarm, "qwertyuiop");
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
private BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {
#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;
if (rawLevel >= 0 && scale > 0) {
level = (rawLevel * 100) / scale;
}
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean charging = status == BatteryManager.BATTERY_STATUS_CHARGING;
if (charging) {
views.setTextViewText(R.id.tvBattery, "Charging: " + level + "%");
if (level == 100) {
views.setTextViewText(R.id.tvBattery, "Battery Full");
}
} else {
views.setTextViewText(R.id.tvBattery, "Battery: " + level + "%");
}
}
};
}
AppWidgetProvider extends android.content.BroadcastReceiver, so you cannot register new BroadcastReceiver to the your AppWidget's context. In your code, you will not receive battery event from your BroadcastReceiver. Refer these previous questions. :)
Android Broadcast Receiver in Widget
Register BroadcastReceiver to Widget (Difference of Context object)
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);
}
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
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