android studio battery percentage example
In this Article Today learn how to check battery level in android programmatically. follow this full tutorial
1.Open Android Studio create a New Project:
2.Click Empty Activity and click next:
3.Renam a file Name and Package Name Click Finish:
4.MainActivity.java:
package com.akash.myapplication;
import android.app.Activity;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
public class MainActivity extends Activity {
int view = R.layout.activity_main;
TextView text;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
text = findViewById(R.id.text);
BatteryManager bm = (BatteryManager)getSystemService(BATTERY_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
int percentage = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
text.setText("Battery Percentage is "+percentage+" %");
}
}
}
5.activity_main.xml:
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/parent"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:gravity = "center"
android:orientation = "vertical">
<TextView
android:id = "@+id/text"
android:textSize = "18sp"
android:textAlignment = "center"
android:text = "batter percentage"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
</LinearLayout>
6.AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.akash.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
7.colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#6200EE</color>
<color name="colorPrimaryDark">#3700B3</color>
<color name="colorAccent">#03DAC5</color>
</resources>
8.strings.xml:
<resources>
<string name="app_name">My Application</string>
</resources>
No comments:
Post a Comment