我有一个播放声音并运行良好的媒体播放器服务,但我希望从较低的声音开始每5秒增加一次铃声音量。我该怎么做?我认为最好使用mediaplayer卷而不是audiomanager,因为这会改变系统音量。
我的服务
public class AlertSound extends Service {
MediaPlayer mp;
String TAG = "DebugMsg";
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.d(TAG, "onStartCommand AlertSound");
if(intent.hasExtra("alertType")){
startSound(intent.getStringExtra("alertType"));
}
else{
startSound("warning");
}
return START_NOT_STICKY;
}
private void startSound(String alarm) {
if(mp==null) {
if(alarm.equals("danger")){
mp = MediaPlayer.create(getApplicationContext(), R.raw.danger_alarm);
}
if(alarm.equals("warning")){
mp = MediaPlayer.create(getApplicationContext(), R.raw.warning_alarm);
}
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mp.start();
}
});
}
}
@Override
public void onDestroy() {
//Log.d(TAG, "StopService AlertSound");
mp.stop();// Stop it
mp.release();// Release it
super.onDestroy();
}
}
答案 0 :(得分:0)
好的,我解决了,工作正常!我使用h.removeCallbacksAndMessages(null)
代替h.removeCallbacks(runnable)
,因为处理程序在服务停止时生成错误
我的代码
public class AlertSound extends Service {
MediaPlayer mp;
String TAG = "DebugMsg";
Handler h = new Handler();
int delay = 7*1000; //1 second=1000 milisecond
float volume=0.20f;
float increment = 0.25f;
Runnable runnable;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.d(TAG, "onStartCommand AlertSound");
if(intent.hasExtra("alertType")){
startSound(intent.getStringExtra("alertType"));
}
else{
startSound("warning");
}
return START_NOT_STICKY;
}
private void startSound(String alarm) {
if(mp==null) {
if(alarm.equals("danger")){
mp = MediaPlayer.create(getApplicationContext(), R.raw.danger_alarm);
mp.setVolume(volume,volume);
h.postDelayed(new Runnable() {
public void run() {
runnable = this;
if(mp!=null) {
volume += increment;
if (volume <= 1.0f) {
mp.setVolume(volume, volume);
Log.d(TAG, "Increase Volume");
h.postDelayed(runnable, delay);
}
else{
stopHandler();
}
}
}
}, delay);
}
if(alarm.equals("warning")){
mp.reset();
mp = MediaPlayer.create(getApplicationContext(), R.raw.warning_alarm);
mp.setVolume(volume,volume);
}
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mp.start();
mp.setVolume(volume, volume);
}
});
}
}
private void stopHandler(){
Log.d(TAG, "stop handler");
h.removeCallbacksAndMessages(null);
}
@Override
public void onDestroy() {
//Log.d(TAG, "StopService AlertSound");
if(mp!=null) {
mp.stop();// Stop it
mp.release();// Release it
}
stopHandler();
super.onDestroy();
}}