我以前發佈過這個問題,沒有人能回答,所以我再次嘗試,因爲這個問題使我的應用程序變得毫無價值。當屏幕超時或用戶點按電源按鈕時,我需要繼續播放聲音。我已經閱讀了幾乎所有關於喚醒鎖的在線文章,我可以找到並且無法使其工作。下面是根據用戶選擇的輸入播放聲音的.Java文件之一。除了當屏幕變暗時聲音停止播放,一切都很好。只是一個說明,我對此很新,所以如果這個代碼是草率或多餘的請讓我知道。喚醒鎖定不起作用
package com.androidsleepmachine.gamble;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class Ship extends Activity implements View.OnClickListener {
public static final Integer[] TIME_IN_MINUTES = { 30, 45, 60, 180, 360 };
public MediaPlayer mediaPlayer;
public Handler handler = new Handler();
public Button button2;
public Spinner spinner2;
public PowerManager.WakeLock wl;
// Initialize the activity
@Override
public void onCreate(Bundle savedInstanceState) {
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"Playwhenoff");
super.onCreate(savedInstanceState);
wl.acquire();
setContentView(R.layout.ship);
button2 = (Button) findViewById(R.id.btn2);
button2.setOnClickListener(this);
spinner2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,
android.R.layout.simple_spinner_item, TIME_IN_MINUTES);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter);
}
// Play the sound and start the timer
private void playSound(int resourceId) {
// Cleanup any previous sound files
cleanup();
// Create a new media player instance and start it
mediaPlayer = MediaPlayer.create(this, resourceId);
mediaPlayer.start();
// Create the timer to stop the sound after x number of milliseconds
int selectedTime = TIME_IN_MINUTES[spinner2.getSelectedItemPosition()];
handler.postDelayed(runnable, selectedTime * 60 * 1000);
}
// Handle button callback
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn2:
playSound(R.raw.ocean_ship);
break;
}
}
protected void onStop() {
cleanup();
super.onStop();
}
// Stop the sound and cleanup the media player
public void cleanup() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
wl.release();
}
// Cancel any previously running tasks
handler.removeCallbacks(runnable);
}
// Runnable task used by the handler to stop the sound
public Runnable runnable = new Runnable() {
public void run() {
cleanup();
}
};
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
wl.release();
}
}
好吧,我想我明白你說的一點點。當我刪除清理();從onStop();當我關閉屏幕時音頻仍然播放,問題就是它不會停下來。我如何解決這個問題 – user2727048
@ user2727048:正如我寫的,音頻播放器通常使用服務進行音頻播放,因此播放可以獨立於此類UI關注運行。您的用戶界面將命令發送到服務以啓動和停止播放。 – CommonsWare
我明白你的意思了,但我對這個真的很陌生,我不知道如何實施從我的活動播放聲音到播放聲音的服務的更改 – user2727048