Get Battery Level and State in Android

Get battery level and state in Android

Here is a code sample that explains how to get battery information.

To sum it up, a broadcast receiver for the ACTION_BATTERY_CHANGED intent is set up dynamically, because it can not be received through components declared in manifests, only by explicitly registering for it with Context.registerReceiver().

public class Main extends Activity {
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level * 100 / (float)scale;
batteryTxt.setText(String.valueOf(batteryPct) + "%");
}
};

@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.main);
batteryTxt = (TextView) this.findViewById(R.id.batteryTxt);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}

Get the exact battery level on android

Get the battery capacity according @user87049's link and use your own function to get the current battery percentage and combine those two to get a current capacity.

int batteryPercentage = getBatteryPercentage() //Your function
double batteryCapacity = getBatteryCapacity() //code from link from user87049. Change it to return value
double currentCapacity = (batteryPercentage * batteryCapacity) / 100

How to get the battery level in background and announce it?

The thing that you want to achieve can be done via intent Service, if you dig in the docs you can find it yourself, here is the link Intent Service, This type of intent can be fired in the background and can be used to perform various simple operations such as yours, because they don't have any interface but rather just operations executed in background.

Also here is a video guide Background Services which you can use for yourself to get battery percentage and announce it after a certain condition

Edit 2:

(Nothing Required in XML as this is a background process/operation)
This is a code to get the battery percentage and announce it using Text to speech in broadcast receiver,

MainActivity.java

package com.example.text_to_speech;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Intent intent=new Intent(this,myBackgroundProcess.class);
intent.setAction("BackgroundProcess");
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
AlarmManager alarmManger= (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManger.setRepeating(AlarmManager.RTC_WAKEUP,0,10,pendingIntent);//change this time based on your liking which will fire the intent

}

}

customerclass- myBackgroundProcess.java

package com.example.text_to_speech;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import java.util.Locale;

import static android.content.Context.BATTERY_SERVICE;

public class myBackgroundProcess extends BroadcastReceiver {
private TextToSpeech mTTS;

@Override
public void onReceive(Context context, Intent intent) {
mTTS = new TextToSpeech(context.getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
int result = mTTS.setLanguage(Locale.US);

if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");

} else {

BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
if(batLevel==100 || batLevel<=10 || batLevel==50)
speak(context,batLevel);

}
} else {
Log.e("TTS", "Initialization failed");

}
}
});

}
public void speak(Context context, int batlevel)
{
mTTS.setPitch(10);
mTTS.setSpeechRate(1);
String text=String.valueOf(batlevel);
mTTS.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

}

In Android Manifest Register the receiver and add intent filter to it as shown below (below application tag)

<receiver android:name=".myBackgroundProcess"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="BackgroundProcess"/>
</intent-filter>
</receiver>

Is it possible to query device state (ie. battery charge remaining) via ADB shell command?

Try this:
adb shell dumpsys battery

It gives all the battery details.



Related Topics



Leave a reply



Submit