2013-03-27 25 views
2

我希望這不是一個類似問題的重複,但一直沒能找到任何幫助我的東西。彈出對話框無論用戶在做什麼

我正在創建一個簡單的雞蛋計時器,它工作得很好。雖然我正在掙扎一件事。 當定時器耗盡時,會啓動一個警報,並彈出一個顯示爲對話框的活動。儘管只有在我打開應用時纔會發生這種情況。如果我打開另一個應用程序,鬧鐘響起,什麼也沒有發生。

所以我的問題是,無論用戶在做什麼,我如何讓對話框彈出?

目前我用於顯示該對話框的方法是這樣的:

private void ShowTimesUp(){ 
    Intent dialogIntent = new Intent(getBaseContext(), TimesUpDialog.class); 
    dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivityForResult(dialogIntent, 1); 
} 

和清單如下所示:

<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> 
+2

你怎麼設置你的計時器?你在使用廣播接收機嗎?如果是這樣,編輯你的文章幷包含它的代碼。 [另請參閱此處](http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/)瞭解可能有所幫助的警報教程。您可以在此示例中替換Toast,並將其更改爲startActivity(),無論當前運行的是什麼,都會導致警報觸發時彈出您的Activity。 – FoamyGuy 2013-03-27 13:26:30

回答

1

試試這個:

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 .:我沒有測試這個,希望它有幫助。

編輯:對於下面的評論

現在,我只是想知道是否有可能獲得來自 意圖由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是一個字符串常量定義一個意圖額外值的鍵和MainActivity是啓動器的活動。

希望這對你有用。

+0

這只是@GyuriMajercsik!現在我只是想知道是否可以從AlarmManager啓動的意圖中得到結果? – frmi 2013-03-27 15:25:07

+0

很高興爲你效勞,不要忘記接受答案......現在,與第二個問題有關...我認爲這是可能的。讓我編輯我的答案。 – 2013-03-27 16:07:14

+0

我無法讓編輯中發佈的代碼正常工作,但僅僅爲了澄清我自己,TIMEOUT常數只是在意圖顯示正確時才推遲? 我想要對話結果的原因是當用戶在對話框中按下按鈕時簡單地關閉鬧鐘。我可以關閉對話框中的警報,但是將警報對象添加到對話框意圖中,然後使用您的初始建議? – frmi 2013-03-27 17:04:57