這裏我試圖確定屏幕是否打開,但按下電源鎖定/解鎖按鈕時似乎不工作。應用程序沒有錯誤,但if-else中的代碼似乎沒有效果。 編輯 現在的代碼工作(感謝Olgun),但媒體播放器回放犯規停止,每一次開/關篩選新的媒體播放器objct創建(多播放)。屏幕開/關檢測
SCBroadcaster.java
public class SCBroadcaster extends BroadcastReceiver {
PowerManager pm;
MediaPlayer mp;
public static boolean wasScreenOn = true;
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
mp = MediaPlayer.create(arg0, R.raw.gale);
if (arg1.getAction().equals(Intent.ACTION_SCREEN_ON)) {
mp.stop();
mp.release();
Toast.makeText(arg0, "oNONONO", Toast.LENGTH_LONG).show();
} else if (arg1.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mp.start();
}
}
}
MainActivity.java
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
BroadcastReceiver bre = new SCBroadcaster();
registerReceiver(bre, filter);
}
protected void onPause() {
super.onPause();
if (SCBroadcaster.wasScreenOn) {
System.out.println("SCREEN TURNED OFF");
} else {
}
}
protected void onResume() {
super.onResume();
if (!SCBroadcaster.wasScreenOn) {
} else {
}
}
}
鏈接中的代碼工作正常,但即使使用停止和釋放方法後,mediaplayer播放也不會停止 – dreamer1989