Battery Receiver
Battery Receiver
package com.example.bt;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
batteryReceiver = new BatteryReceiver(tv);
registerReceiver(batteryReceiver,new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(batteryReceiver);
}
}
package com.example.bt;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.TextView;
@Override
public void onReceive(Context context, Intent intent) {
int percentage = intent.getIntExtra("level",0);
if (percentage !=0){
tv.setText(percentage +"%");
}
}
}
XML
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/tv"
android:textSize="40dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>