这是我的主要活动。 package com.example.simeon.cookingbook.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import com.example.simeon.cookingbook.R;
import com.example.simeon.cookingbook.services.BackgroundMusic;
public class MainActivity extends AppCompatActivity {
Intent srv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.srv = new Intent(this, BackgroundMusic.class);
startService(srv);
}
@Override
protected void onDestroy() {
super.onDestroy();
stopService(srv);
}
@Override
protected void onPause() {
super.onPause();
stopService(srv);
}
@Override
protected void onStop() {
super.onStop();
stopService(srv);
}
@Override
protected void onRestart() {
super.onRestart();
startService(srv);
}
@Override
protected void onResume() {
super.onResume();
startService(srv);
}
}
那是BackgroundMusic服务。
package com.example.simeon.cookingbook.services;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import com.example.simeon.cookingbook.R;
public class BackgroundMusic extends Service {
private static final String TAG = null;
public MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.background);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return START_STICKY;
}
}
我有其他活动,我希望在我的应用程序打开时听到音乐,但是当它转到后台时,我不想让音乐继续播放。我尝试使用BaseActivityClass并阅读了很多内容,但仍然没有解决方案。请帮助,提前谢谢。
答案 0 :(得分:0)
使用完MediaPlayer后,您需要使用release()
方法发布它。我想你服务的onDestroy()
方法是个好地方:
public class BackgroundMusic extends Service {
private static final String TAG = null;
public MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.background);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return START_STICKY;
}
public int onDestroy() {
player.release();
}
}