我的应用程序中有很多活动,我希望音乐在后台独立播放,即使在切换活动时也是如此。 Currenly当我切换到另一个活动时,音乐会暂停一段时间,然后从头开始。 如何在后台独立播放音乐?
我的代码:
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();
}
}
然后我将这种活动扩展到另一项活动中:
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;
};
});
}
}