There are many activities in my app, and I want music to play independently in the background, even while switching activities. Currenly When I switch to another activity, music stops for a while then starts from the beginning. How to make music play independently in the background?
My code:
public class StartMusic extends AppCompatActivity {
MediaPlayer player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
player = MediaPlayer.create(this, R.raw.musicname);
player.setLooping(true);
player.start();
}
protected void onDestroy() {
//other codes
super.onDestroy();
player.stop();
}
protected void onStop() {
super.onStop();
player.pause();
}
protected void onResume() {
super.onResume();
player.start();
}
}
Then I extend this acivity in another activities:
public class OpenerPlay extends StartMusic {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opener_play);
String uripath = "android.resource://com.example.android.appname/" + R.raw.musicname;
VideoView videoView = (VideoView) findViewById(R.id.id);
Uri uri = Uri.parse(uripath);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
final Intent intent = new Intent (this, MainActivity.class);
final TextView button = (TextView) findViewById(R.id.bunton);
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
startActivity(intent);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_UP:
return true;
}
return true;
};
});
}
}
Use a
Service
to play your music. More aboutServices
can be found hereAfterwards you can also run your
Service
in a different process, which results into having more memory available, but it depends on your case if that's necessary or not. More about processes can be found here