我正在尝试创建一个应该在一段时间后响铃的闹钟应用程序。 它在屏幕打开时有效;我打开应用程序,5秒后闹钟响起。这正是我想要的。
现在,我希望我的应用程序在屏幕关闭时以相同的方式运行。因此,如果我打开我的应用程序然后关闭屏幕,我希望应用程序在5秒后打开屏幕,然后响铃。
我尝试SCREEN_BRIGHT_WAKE_LOCK
(确实输入了所需的权限),但它没有用。警报响了半秒然后关掉了。屏幕根本没有打开。此外,SCREEN_BRIGHT_WAKE_LOCK
已被弃用,文档建议使用FLAG_KEEP_SCREEN_ON
,这仅在屏幕已打开时才有用,我们希望保持这种方式。不要从关闭状态打开它。
我需要做些什么才能解决上述问题?使用服务?此外,屏幕被数字锁定锁定。
这是我的代码,仅在屏幕开启时才有效:
public class AlarmReceiverActivity extends Activity {
private MediaPlayer mMediaPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_alarm_receiver);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
stopAlarm.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
mMediaPlayer.stop();
mMediaPlayer.release();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
try {
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
System.out.println("Oops");
}
}
} catch (IOException e1) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
}
答案 0 :(得分:1)
我最近正在处理这个问题。 这对我有用:
public class YourActivity extends Activity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
...
}
有用的链接:
Android Activity Not Showing When Screen is Woken Up and Lock Screen Not Disabling
http://weimenglee.blogspot.co.il/2013/04/android-tip-waking-up-screen-and.html
Android Galaxy S4 -- Activity that is visible over lock screen
也不要在活动中使用对话框主题!!!