MainActivity.kt
package com.example.jetpack
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get battery capacity and show it on text view
applicationContext.batteryCapacity?.apply {
textView.text = "Battery Capacity\n${this.toInt()} mAh"
}
}
}
// extension property to get battery capacity
val Context.batteryCapacity:Double?
get() {
val powerProfileClass = "com.android.internal.os.PowerProfile"
try {
(Class.forName(powerProfileClass).getConstructor(Context::class.java)
.newInstance(this)).apply {
return Class.forName(powerProfileClass)
.getMethod("getAveragePower", String::class.java)
.invoke(this, "battery.capacity") as Double
}
}catch (e: Exception){
e.printStackTrace()
}
return null
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#EDEAE0"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
android:gravity="center"
android:padding="32dp"
android:textColor="#0014A8"
android:textSize="35sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.25"
tools:text="TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>

- android kotlin - ImageView set image from Uri
- android kotlin - Get battery percentage programmatically
- android kotlin - Get battery level programmatically
- android kotlin - Get battery voltage programmatically
- android kotlin - Get battery status programmatically
- android kotlin - On back button pressed example
- android kotlin - Get string resource by name
- android kotlin - Get screen size category
- android kotlin - Get API level programmatically
- android kotlin - Play default ringtone programmatically
- android kotlin - Enable disable bluetooth programmatically
- android kotlin - Change screen orientation programmatically
- android kotlin - Change orientation without restarting activity
- android kotlin - Get screen density programmatically
- android kotlin - Convert pixels to dp programmatically