B4A Library BatteryView

It is a "partly" wrap for this Github project. If anyone has use for this I will add some more getters/setters that are not at present available in the original Github project (such as colors, etc).

Please note that I am driving this view via a B4A code module that makes use of inline Java code to extract some battery information.

Sample Code:
B4X:
#Region  Project Attributes
    #ApplicationLabel: b4aBatteryView
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
 
    Dim t As Timer

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

    Private bv1 As BatteryView
    Private bu As BatteryUtilities
 
    Dim batterystatus(11) As Int
 
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("main")
    bu.Initialize
 
    batterystatus = bu.BatteryInformation
    bv1.Level = batterystatus(0)
    If batterystatus(8) = 1 Then
        bv1.Charging = True
    Else
        bv1.Charging = False 
    End If
 
 
    t.Initialize("t", 20000)
 
 
End Sub

Sub Activity_Resume
 
    t.Enabled = True

End Sub

Sub Activity_Pause (UserClosed As Boolean)
 
    t.Enabled = False

End Sub

Sub t_tick
 
    batterystatus = bu.BatteryInformation
    bv1.Level = batterystatus(0)
    bv1.Level = batterystatus(0)
    If batterystatus(8) = 1 Then
        bv1.Charging = True
    Else
        bv1.Charging = False
    End If
 
End Sub

Code in module BatteryUtilities:
B4X:
'Class module
Sub Class_Globals
    Private nativeMe As JavaObject
 
End Sub
'Initializes the object.
Public Sub Initialize
    nativeMe = Me
End Sub
'Return information about the battery status. It returns the following 11 values in an integer Array:
'EXTRA_LEVEL = current battery level, from 0 To EXTRA_SCALE.
'EXTRA_SCALE = the maximum battery level possible.
'EXTRA_HEALTH = the current health constant.
'EXTRA_ICON_SMALL = the resource ID of a small status bar icon indicating the current battery state.
'EXTRA_PLUGGED = whether the device is plugged into a Power source; 0 means it is on battery, other constants are different types of Power sources.
'EXTRA_STATUS = the current status constant.
'EXTRA_TEMPERATURE = the current battery temperature.
'EXTRA_VOLTAGE = the current battery voltage level.
'A value indicating if the battery is being charged or fully charged (If neither it returns 0 Else it returns 1)
'A value indicating if it is charging via USB (0 = Not USB, 2 = USB)
'A value indicating if it is charging via AC (0 = Not AC, 1 = AC)
Public Sub getBatteryInformation () As Int()

Dim dummy As Int = 1
Dim batteryInfo(11)  As Int
batteryInfo = nativeMe.RunMethod("getBatteryInformation",Null)
Return batteryInfo

End Sub


#If Java

import android.os.BatteryManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

  public int[] getBatteryInformation() {

        int[] mybat = new int[11];
    Intent batteryIntent = ba.context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        mybat[0] = level;
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        mybat[1] = scale;
        int health = batteryIntent.getIntExtra(BatteryManager.EXTRA_HEALTH,-1);
        mybat[2] = health;
        int icon_small = batteryIntent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL,-1);
        mybat[3] = icon_small;
        int plugged = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1);
        mybat[4] = plugged;
//        boolean present = batteryIntent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
        int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
        mybat[5] = status;
//        String technology = batteryIntent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
        int temperature = batteryIntent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,-1);
        mybat[6] = temperature;
        int voltage = batteryIntent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,-1);
        mybat[7] = voltage;
//        int ac = batteryIntent.getIntExtra("plugged",BatteryManager.BATTERY_PLUGGED_AC);
//        mybat[8] = ac;
//        int usb = batteryIntent.getIntExtra("plugged",BatteryManager.BATTERY_PLUGGED_USB);
//        mybat[9] = usb;

        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                     status == BatteryManager.BATTERY_STATUS_FULL;
        mybat[8] = 0;
        if (isCharging == true) {
           mybat[8] = 1;
        }

        // How are we charging?
        mybat[9] = 0;
        mybat[10] = 0;
        int chargePlug = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        if (usbCharge == true) {
           mybat[9] = 2;
        }

        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
        if (acCharge == true) {
           mybat[10] = 1;
        }

        return mybat;
  }






#End If

You need to enable the JavaObject library.
Plug your device into you PC/Laptop USB post and see the charging taking place (updated every 5 seconds). Unplug your device from the USB port and see the battery level being displayed inside the battery.


Plugged into USB port and charging:
charging.png


Unplugged from USB port and showing current battery level:
notcharging.png


The color of the battery should change to RED if the battery level drops below 35%

Posting the B4A lib files and a sample project
 

Attachments

  • BatteryViewLibFiles.zip
    6.5 KB · Views: 697
  • b4aBatteryView.zip
    9.6 KB · Views: 660
Last edited:

Wolli013

Well-Known Member
Licensed User
Longtime User
Verry Nice Johan

How can I select the technology?
// String technology = batteryIntent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
 

Johan Schoeman

Expert
Licensed User
Longtime User
Verry Nice Johan

How can I select the technology?
// String technology = batteryIntent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
See attached sample project
 

Attachments

  • b4aBatteryView1.zip
    9.8 KB · Views: 454

Harris

Expert
Licensed User
Longtime User
For this and the progress lib, I get error trying to open main in Designer.
App dies on:
Line 35: Activity.LoadLayout("main")

** Service (starter) Create **
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
Error occurred on line: 35 (Main)
java.lang.RuntimeException: java.lang.RuntimeException: unknown type
at anywheresoftware.b4a.keywords.LayoutBuilder.loadLayout(LayoutBuilder.java:166)
at anywheresoftware.b4a.objects.ActivityWrapper.LoadLayout(ActivityWrapper.java:209)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:708)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:340)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:247)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:134)
at JHS.BatteryProgressView.main.afterFirstLayout(main.java:102)
at JHS.BatteryProgressView.main.access$000(main.java:17)
at JHS.BatteryProgressView.main$WaitForLayout.run(main.java:80)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6914)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
 

Harris

Expert
Licensed User
Longtime User
Got it...
Added customview and saved.
Works fine now.

Thanks
 

victormedranop

Well-Known Member
Licensed User
Longtime User
estrange behavior, with my hardware 4.2.2 said battery full. no matter is it's connected to the charger o
with any ideas?

Victor
 

Johan Schoeman

Expert
Licensed User
Longtime User
Have added some additional setters - see the code in the B4A project. New B4A library files and sample project attached. Also the Java project.

1.png


Ignore the value being displayed in the below image - have simulated it. Does not correspond with actual battery level of the device. Code in attached B4A project is however correct and will display the correct battery level.

2.png



Sample Code:
B4X:
#Region  Project Attributes
    #ApplicationLabel: b4aBatteryView
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
 
    Dim t As Timer

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

    Private bv1 As BatteryView
    Private bu As BatteryUtilities
 
    Dim batterystatus(11) As Int
 
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("main")
    bu.Initialize
 
    batterystatus = bu.BatteryInformation
    bv1.Level = batterystatus(0)
    If batterystatus(8) = 1 Then
        bv1.Charging = True
    Else
        bv1.Charging = False
    End If
 
    bv1.BatteryBackgroundColor = Colors.Transparent
    bv1.SmallRectangleColor = Colors.Blue
    bv1.WarningLevel = 70
    bv1.ChargingColor = Colors.Yellow
    bv1.AboveWaringLevelColor = Colors.Cyan
    bv1.BelowWaringLevelColor = Colors.Magenta
    bv1.BatteryMainOutlineColor = Colors.Red
    bv1.BatteryTextColor = Colors.White
 
    Dim battech As String = bu.BatteryTechnolgy
    Log("BatteryTechnology = " & battech)
 
    t.Initialize("t", 1000)
 
 
End Sub

Sub Activity_Resume
 
    t.Enabled = True

End Sub

Sub Activity_Pause (UserClosed As Boolean)
 
    t.Enabled = False

End Sub

Sub t_tick
 
    batterystatus = bu.BatteryInformation
    bv1.Level = batterystatus(0)
    If batterystatus(8) = 1 Then
        bv1.Charging = True
    Else
        bv1.Charging = False
    End If
 
End Sub
 

Attachments

  • b4aLibFiles.zip
    7.2 KB · Views: 462
  • b4aBatteryView.zip
    9.9 KB · Views: 450
  • TheJavaCode.zip
    6.1 KB · Views: 415
Last edited:

alizeti

Member
Licensed User
Is there something similar for ios?!?!?
Looks really nice and would like to have a bettery level gauge for iOS!!!
 

Johan Schoeman

Expert
Licensed User
Longtime User
Is there something similar for ios?!?!?
Looks really nice and would like to have a bettery level gauge for iOS!!!
I don't do iOS. Android is difficult enough for me at this stage...:confused:
 

Harris

Expert
Licensed User
Longtime User
I don't do iOS. Android is difficult enough
That's where B4X comes in so nicely - all three platforms - one base source (essentially)!
It will take time for many of us to break our old habits and shift gears to the newest \ greatest model.
Old dogs like me are hard to teach new tricks...
 
Top