GameChanger
GameChanger

Reputation: 179

How to prevent music to stop after the phone's screen goes off?

I am making an application which play background music. And when my phone's screen goes off(or sleep) then the music stops and I want it to also play after the screen goes's off.

This is My code.

MediaPlayer ring= MediaPlayer.create(MainActivity.this,R.raw.backgroundmusic);
ring.start();
ring.setLooping(true);

Upvotes: 0

Views: 528

Answers (2)

Raman Saini
Raman Saini

Reputation: 435

MediaPlayer class can be used to control playback of audio/video files and streams. An example on how to use the methods in this class can be found in VideoView. MediaPlayer

public class SoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;
    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.idil);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }
    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {

    }
    public void onPause() {

    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}

  Intent svc=new Intent(this, SoundService.class);
  startService(svc);

Make sure You've added your service to the menifest.

<service android:enabled="true" android:name=".SoundService" />

Upvotes: 1

viz
viz

Reputation: 1277

You should consider using Service.

Upvotes: 0

Related Questions