Search code examples
androidandroid-fragmentactivitybackground-musicbackground-media-player

How to stop playing background music on fragmentActivity


I have a Mainactivity extends fragmentActivity (not sure if relevant) and it plays a background music fine. I want the music to stop when you leave the activity. I minimized the codes below. I am getting a nullpoint exception on the onPause() lifecycle of the Activity.

public class MainActivitytest extends FragmentActivity implements
    ActionBar.TabListener{

private String[] tabs = {"Colors and Shapes", "Letters and Numbers", "CVC and Sight Words", "Adjectives", "Simple Sentences", "Reading Comprehension"};
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private int myShuffledSize;
private Context context;
public static final String PREFS_NAME = "MyPrefsFile";
public MediaPlayer player;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    Intent intent = new Intent(this, MusicService.class);
    startService(intent);

    new SetupViews().invoke();  //setup fragment views
}

public void onResume() {
    super.onResume();
    MediaPlayer player = MediaPlayer.create(MainActivitytest.this, R.raw.bgmusic3);
    player.setLooping(true);
    player.setVolume(100, 100);
    player.start();

}
public void onPause(){
    super.onPause();
    //player.stop();  //causes null pointer exception
}

Solution

  • After doing much more research, I accomplished what I want with service, something new I learned. Here is the code i used

    public class MainActivitytest extends FragmentActivity implements
        ActionBar.TabListener {
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    public final static String MUSIC_BACKGROUND = "com.example.myfirstapp.MESSAGE";
    
    private String[] tabs = {"Colors and Shapes", "Letters and Numbers", "CVC and Sight Words", "Adjectives", "Simple Sentences", "Reading Comprehension"};
    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    private Context context;
    public static final String PREFS_NAME = "MyPrefsFile";
    
    private boolean mIsBound = false;
    private MusicService mServ;
    private ServiceConnection Scon =new ServiceConnection(){
    
        public void onServiceConnected(ComponentName name, IBinder
                binder) {
    
            mServ = ((MusicService.ServiceBinder)binder).getService();
        }
    
        public void onServiceDisconnected(ComponentName name) {
            mServ = null;
        }
    };
    
    void doBindService(){
        bindService(new Intent(this,MusicService.class),
                Scon,Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }
    
    void doUnbindService()
    {
        if(mIsBound)
        {
            unbindService(Scon);
            mIsBound = false;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
    
        new SetupViews().invoke();  //setup fragment views
    }
    
        public void onPause(){
        super.onPause();
        Intent intent = new Intent(this, MusicService.class);
        stopService(intent);
    

    Now my service class

    package info.androidhive.tabsswipe;
    
    import android.app.Service;
    import android.content.Intent;
    import android.media.MediaPlayer;
    import android.media.MediaPlayer.OnErrorListener;
    import android.os.Binder;
    import android.os.IBinder;
    import android.widget.Toast;
    
    public class MusicService extends Service  implements MediaPlayer.OnErrorListener {
    private final IBinder mBinder = new ServiceBinder();
    MediaPlayer mPlayer;
    private int length = 0;
    
    public MusicService() {
    }
    
    public class ServiceBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    
    }
    
    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
    
        mPlayer = MediaPlayer.create(this, R.raw.bgmusic3);
        mPlayer.setOnErrorListener(this);
    
        if (mPlayer != null) {
            mPlayer.setLooping(true);
            mPlayer.setVolume(100, 100);
        }
    
    
        mPlayer.setOnErrorListener(new OnErrorListener() {
    
            public boolean onError(MediaPlayer mp, int what, int
                    extra) {
    
                onError(mPlayer, what, extra);
                return true;
            }
        });
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mPlayer.start();
        return START_STICKY;
    }
    
    public void pauseMusic() {
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
            length = mPlayer.getCurrentPosition();
    
        }
    }
    
    public void resumeMusic() {
        if (mPlayer.isPlaying() == false) {
            mPlayer.seekTo(length);
            mPlayer.start();
        }
    }
    
    public void stopMusic() {
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPlayer != null) {
            try {
                mPlayer.stop();
                mPlayer.release();
            } finally {
                mPlayer = null;
            }
        }
    }
    
    public boolean onError(MediaPlayer mp, int what, int extra) {
    
        Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
        if (mPlayer != null) {
            try {
                mPlayer.stop();
                mPlayer.release();
            } finally {
                mPlayer = null;
            }
        }
        return false;
    }
    
    
    }
    

    Include this in the manifest

        <service android:name=".MusicService" />
        <activity
            android:name="info.androidhive.tabsswipe.MainActivitytest"
            android:label="@string/app_name" >
    
    
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
    

    This works even on my fragmented view. I learned a lot today. Hope this helps someone else like me.