我希望这不是类似问题的重复,但我找不到任何对我有帮助的东西。
我正在创建一个简单的煮蛋计时器,它运行良好。尽管我在挣扎一件事。 当计时器用完时,将启动警报并弹出显示为对话框的 Activity 。虽然只有当我打开应用程序时才会发生这种情况。如果我打开另一个应用程序并且闹钟响了,什么也不会发生。
所以我的问题是,无论用户在做什么,我如何让对话框弹出?
目前我显示对话框的方法是这样的:
private void ShowTimesUp(){
Intent dialogIntent = new Intent(getBaseContext(), TimesUpDialog.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(dialogIntent, 1);
}
list 看起来像这样:
<activity android:name=".Home"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".TimesUpDialog" android:theme="@android:style/Theme.DeviceDefault.Dialog"></activity>
最佳答案
试试这个:
public static final int TIMEOUT = 60 * 1000;
...
Intent dialogIntent = new Intent(getBaseContext(), TimesUpDialog.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(YourApplication.getInstance().getBaseContext(), 0,
dialogIntent, dialogIntent.getFlags());
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + TIMEOUT, intent);
我认为您不需要任何其他计时器逻辑。
P.S.:我没有测试这个,希望它有帮助。
编辑:以下评论中提到的问题的可能解决方案
Now I am just wondering if it is possible to get a result from the intent started by the AlarmManager?
上面的代码应该改成这样:
Intent startApplicationIntent = new Intent(getBaseContext(), MainActivity.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startApplicationIntent.putExtra(START_DIALOG, true);
PendingIntent intent = PendingIntent.getActivity(YourApplication.getInstance().getBaseContext(), 0,
startApplicationIntent, startApplicationIntent.getFlags());
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + TIMEOUT, intent);
现在,在您的 MainActivity
的 onStart()
方法中,您可以执行以下操作:
boolean startDialog = getIntent().getBooleanExtra(START_DIALOG, false);
if (startDialog) {
Intent dialogIntent = new Intent(MainActivity.this, TimesUpDialog.class);
startActivityForResult(dialogIntent, REQUEST_CODE_CONSTANT);
}
其中,START_DIALOG
是一个字符串常量,用于定义 intent 额外值的键,MainActivity
是 Launcher Activity 。
希望这对你有用。
关于android - 无论用户在做什么都弹出对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15659974/