我调试过了,确实执行到 showAlertDialog(context); 了,我在 logcat 里看到了。代码是这样的:
if (pm.isScreenOn()) {
Log.v("remind", "show alert");
showAlertDialog(context);
}
在下面那个不能显示的情况下有时候好像会一下子显示出来很多。因为一个对话框只有很少的阴影,因为前面说的那种情况阴影很多,所以可能有很多。然后在这种情况下点击屏幕就没反应了,奇怪的是点击菜单、主页、返回有反应。
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" >
</uses-permission>
BroadcastReceiver mScreenStateReceiver = new ScreenStateReceiver();
IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mScreenStateReceiver, screenStateFilter);
下面的不会显示:
public class ScreenStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
while(true) {
try {
Thread.sleep(3 * 1000);
} catch (Exception e) {
System.out.println("Error: " + e);
}
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if(pm.isScreenOn()) {
showAlertDialog(context);
}
else
return;
}
}
public void showAlertDialog(Context context) {
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
builder.setTitle("提醒")
.setMessage("你正在看的东西有用吗?")
.setPositiveButton("有用", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton("没用", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert);
AlertDialog alert = builder.create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alert.show();
}
}
下面这样就能显示了:
public void onReceive(Context context, Intent intent) {
try {
Thread.sleep(3 * 1000);
} catch (Exception e) {
System.out.println("Error: " + e);
}
showAlertDialog(context);
}