Search code examples
javaandroidxmlbackaudio-playerandroid-music-player

Implementing back button (physical) Android when in activity


I'm trying to implement back buttons on an Android app. The image button is working correctly (ie it goes to previous screen and stops music. Clicking the physical back button causes the app to exit with an error. How can this be fixed? Below is my current code...

    package com.mellowbluestuff;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import java.util.List;

import com.example.android.searchabledict.R;
import com.mellowbluestuff.*;

import android.os.Bundle;
import android.os.Vibrator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;


public class MusicPlayerA extends Activity {

    private MediaPlayer mediaPlayer;
    public TextView songName, duration;
    private double timeElapsed = 0, finalTime = 0;
    private int forwardTime = 2500, backwardTime = 2500;
    private Handler durationHandler = new Handler();
    private SeekBar seekbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //set the layout of the Activity
        setContentView(R.layout.musicplayerview);
        //initialize views
        initializeViews();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            if (isFinishing()) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
        }
    }

    public void initializeViews(){
        songName = (TextView) findViewById(R.id.songName);
        mediaPlayer = MediaPlayer.create(this, R.raw.druidsad);
        finalTime = mediaPlayer.getDuration();
        duration = (TextView) findViewById(R.id.songDuration);
        seekbar = (SeekBar) findViewById(R.id.seekBar);
        songName.setText("Druids Ad");  
        seekbar.setMax((int) finalTime);
        seekbar.setClickable(true);
    }

    // play mp3 song
    public void play(View view) {
        mediaPlayer.start();
        timeElapsed = mediaPlayer.getCurrentPosition();
        seekbar.setProgress((int) timeElapsed);
        durationHandler.postDelayed(updateSeekBarTime, 100);
    }

    //handler to change seekBarTime
    private Runnable updateSeekBarTime = new Runnable() {
        public void run() {
            //get current position
            timeElapsed = mediaPlayer.getCurrentPosition();
            //set seekbar progress
            seekbar.setProgress((int) timeElapsed);
            //set time remaining
            double timeRemaining = finalTime - timeElapsed;
            duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));

            //repeat yourself that again in 100 miliseconds
            durationHandler.postDelayed(this, 100);
        }
    };

    // pause mp3 song
    public void pause(View view) {
        mediaPlayer.pause();
    }

    // go forward at forwardTime seconds
    public void forward(View view) {
        //check if we can go forward at forwardTime seconds before song endes
        if ((timeElapsed + forwardTime) <= finalTime) {
            timeElapsed = timeElapsed + forwardTime;

            //seek to the exact second of the track
            mediaPlayer.seekTo((int) timeElapsed);
        }
    }

    // go backwards at backwardTime seconds
    public void rewind(View view) {
        //check if we can go back at backwardTime seconds after song starts
        if ((timeElapsed - backwardTime) > 0) {
            timeElapsed = timeElapsed - backwardTime;

            //seek to the exact second of the track
            mediaPlayer.seekTo((int) timeElapsed);
        }
    }

     // handler for back button used on music player screen
     public void BackButton2 (View view) {

        MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
        mMediaPlayer.start();

        Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vib.vibrate(200);

        Intent mus = new Intent (this, Music.class);
        startActivity(mus);
     }

    // handler for home button used on all screens
    public void BackButton (View view) {

        MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
        mMediaPlayer.start();

        Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vib.vibrate(200);

        Intent mn = new Intent (this, Music.class);
        startActivity(mn);
     }

}

And the XML

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:background="@drawable/fabricblacksmr"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

      <ImageButton
        android:id="@+id/BackButton2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:onClick="BackButton2"
        android:src="@drawable/buttonback"
        android:background="#00000000" />   

    <TextView
        android:id="@+id/songName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:paddingTop="4dp"
        android:text="songName" />

    <ImageView
        android:id="@+id/mp3Image"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="#00000000"
        android:paddingBottom="8dp"
        android:paddingTop="8dp"
        android:onClick="play"
        android:src="@drawable/anglo" />

        <TextView
            android:id="@+id/songDuration"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="5dp"
            android:text="Best enjoyed with stereo headphones" />

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="15dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/media_rew"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="rewind"
            android:src="@android:drawable/ic_media_rew" />

        <ImageButton
            android:id="@+id/media_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="pause"
            android:src="@android:drawable/ic_media_pause" />

        <ImageButton
            android:id="@+id/media_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="play"
            android:src="@android:drawable/ic_media_play" />

        <ImageButton
            android:id="@+id/media_ff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="forward"
            android:src="@android:drawable/ic_media_ff" />
    </LinearLayout>

</LinearLayout>

Solution

  • Override onBackPressed() with your code like this:

    @Override
    public void onBackPressed() {
      Your code
    }