Search code examples
androidandroid-alarmsbatterylevel

I'm trying to make an android app where an alarm plays when the battery gets under 10%. Why isn't my code working?


The audio file (.mp3) gets played when I don't use the onPreparedListener, but I get an error after the file tries to replay after some time (because it's not listening for the state obviously). So basically the code is checking the battery state and if it's 10% or below it plays the alarm sound, I also have a button which I can click to stop the sound. Now with the onPreparedListener the alarm sound doesn't get played anymore. What am I doing wrong?

    tv_battery = (TextView) findViewById(R.id.tv_battery);
    final MediaPlayer mp = MediaPlayer.create(this, R.raw.alarm);
    Button b = (Button) findViewById(R.id.stop_alarm);
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);


    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if(mp.isPlaying()) {
                mp.stop();
                mp.release();
            }
        }
    });
    runnable = new Runnable() {
        @Override
        public void run() {
            int level = (int) batteryLevel();

            tv_battery.setText("Battery: " + level + "%");
            handler.postDelayed(runnable, 5000);

            if(level <=  10) {

                mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                    @Override
                    public void onPrepared(final MediaPlayer mp) {
                        CountDownTimer count = new CountDownTimer(7000, 1000) {

                            public void onTick(long millisUntilFinished) {
                                mp.start();
                            }

                            public void onFinish() {
                                //code fire after finish
                                mp.stop();
                            }

                        };
                        count.start();
                    }

Solution

  • I think you have place mp.start(); on wrong place please move it before count.start(); as below :

    CountDownTimer count = new CountDownTimer(7000, 1000) {
         public void onTick(long millisUntilFinished) {
    
         }
    
         public void onFinish() {
                //code fire after finish
                mp.stop();
         }
    };
    mp.start();
    count.start();
    

    Also correct below condition if media player already started when battery is under 10 otherwise media player again prepared even after started :

    if(level <=  10 && !mp.isPlaying()) {