2011-07-06 27 views
1

我在我的應用程序中使用AlarmManager。我想在報警發生時向用戶顯示警告。 我使用了一個AlertDialog,但它給出了一個錯誤。我怎麼解決這個問題? 我想要發出警告音和振動。任何鏈接或代碼。AlarmManager問題?

public class AReceiver extends BroadcastReceiver{ 

AlertDialog alertDialog; 

public void onReceive(Context context, Intent intent) { 

    alertDialog = new AlertDialog.Builder(this).create(); // Error here: The constructor AlertDialog.Builder is undefined. 
    alertDialog.setTitle("title"); 

    alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 

      public void onClick(DialogInterface dialog, int which) { 
      return; 
     } }); 

} 
} 
+0

@@你檢查realuser回答? – Nikhil

+0

@@ realuser,如果你發現這個答案是正確的,那麼對它更有幫助。 – Nikhil

回答

4

嗨,你不能使用AlertDialog在BroadcastReceiver ..

調用另外一個Activity類BroadcastReciver像下面。

Intent myIntent = new Intent(context, AlarmActivity.class); 
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
context.startActivity(myIntent); 

而在這個類中,您使用了警報對話框。

+0

非常感謝Nik,它非常有用。 – realuser

0

我可以告訴你如何解決這個問題的主要想法。

  • AlarmManager中使用的BroadcastReceiver是具有靜態上下文的靜態類。

  • AlertDialog應該在非靜態上下文而不是靜態上下文中執行。

我對這個問題有兩種解決方案。

所以,當你在一個非靜態場景中獲得的報警事件,你可以使用AlertDialog。

0

晚,但也許有人仍然是有用的:

更正像下面的代碼:

alertDialog = new AlertDialog.Builder(context).create(); // Now The constructor AlertDialog.Builder is defined.