當android中的鬧鐘響起時,我想創建一個AlertDialog。另外,我想創建一個通知,具體取決於用戶在對話框的單選按鈕中單擊的選項。 當我嘗試使用context
或getApplicationContext()
時出現問題。在課堂上使用上下文擴展BroadcastReceiver
這是我的代碼:
public void onReceive(final Context context, Intent intent)
{
final CharSequence[] items = {" I'm taking the dose now! "," Remind again in ten minutes. "," Ignore for now. "};
String doseName = intent.getStringExtra("doseName");
Toast.makeText(context, "Take medicine: " + doseName, Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("It's time for your medicine.");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item)
{
case 0:
Toast.makeText(context, "Good.", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(context, "Reminder set in ten minutes.", Toast.LENGTH_SHORT).show();
break;
case 2:
Intent service1 = new Intent(context, DoseAlarmService.class);
service1.putExtra("doseName", doseName);
context.startService(service1);
break;
}
}
});
levelDialog = builder.create();
levelDialog.show();
}
我一直在使用getApplicationContext
代替context
開關盒內試過了,但是這是確切的錯誤我得到:
The method getApplicationContext() is undefined for the type new DialogInterface.OnClickListener(){}
如何任何建議前進?
編輯:
截至目前,這些是我已經試過:
public void onReceive(final Context context, Intent intent)
{
ctx = context;
final CharSequence[] items = {" I'm taking the dose now! "," Remind again in ten minutes. "," Ignore for now. "};
String doseName = intent.getStringExtra("doseName");
Toast.makeText(ctx, "Take medicine: " + doseName, Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(ctx.getApplicationContext());
builder.setTitle("It's time for your medicine.");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item)
{
case 0:
Toast.makeText(ctx, "Good.", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(ctx, "Reminder set in ten minutes.", Toast.LENGTH_SHORT).show();
break;
case 2:
Intent service1 = new Intent(ctx.getApplicationContext(), DoseAlarmService.class);
service1.putExtra("doseName", doseName);
ctx.startService(service1);
break;
}
}
});
levelDialog = builder.create();
levelDialog.show();
}
而且,而是採用ctx
,我心中已經直接使用context.getApplicationContext()
和檢查。它不起作用。
此外,當我註釋掉所有有問題的領域,只是運行,以驗證對話框輪番上漲,我得到這個異常:
07-23 13:26:21.316: E/AndroidRuntime(1756): java.lang.RuntimeException: Unable to start receiver com.dosemanager.ui.DoseAlarmReceiever: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
請幫幫忙!
你可以使用context.getApplicationContext()。 –
現在,這是另一個問題。沒有活動就無法顯示對話框。創建新的活動並在那裏顯示對話框。 –
嘗試使用'Activity cxt =(Activity)上下文;'並使用cxt作爲你的上下文 –