Android Programming

Hands On No. 15 : Working with Battery and Torch

Resources for working with Battery

Source Code of MainAcivity.java
import androidx.appcompat.app.AppCompatActivity;

import android.os.BatteryManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button showstatus = (Button) findViewById(R.id.showstatus);
showstatus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

BatteryManager bm = (BatteryManager)getSystemService(BATTERY_SERVICE);

int percentage = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
percentage = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
}
Toast.makeText(getApplicationContext(),"Battery Percentage is " + percentage + " %",Toast.LENGTH_LONG).show();


}
});

}
}
Source Code of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".workingwithbattery" >

<Button
android:id="@+id/showstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Status" android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
/>

</LinearLayout>