Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

Battery Low / Full status

meetdilip

Well-Known Coder
Hi, I am trying to get an audio notification when the Android battery is full and low.


I understand the logic. As in, check battery status, then if battery_full run Android Media Player. I am trying to use it for my personal needs. This is the MainActivity.java I have

Java:
package me.adminweb.batterydost;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.BatteryManager;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

        // Are we charging / charged?

        int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL;

       // How are we charging?
        int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

        if(status == BatteryManager.BATTERY_STATUS_FULL){

            //Play sound using Android MediaPlayer

            MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.batteryfull);
            mediaPlayer.start(); // no need to call prepare(); create() does that for you
        }


Looks like I am missing a few things. It would be nice if I can get some help building this app
 
I'm familiar with Java but on Windows only, not on Android, so it seems unlikely I'll be able to help you.
But it seems to me you are not saying what the actual problem is, except for "missing a few things". Also it is not clear how this snippet of code (which isn't even complete) fits in the bigger picture. You may want to think about providing some more relevant detail.
 
If you are trying to get it on demand like any time, not just in that app, then I do not know how,
but if you want it just while your app is running, use a listener not just an onCreate thing.
X E.
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom