在Android中设置通知时出错

时间:2013-07-26 07:34:21

标签: android notifications

当我通过扩展getApplicationContext()的适配器类在我的应用中设置通知时,我在PagerAdapter收到错误。以下是我的代码:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH,6);
cal.set(Calendar.YEAR, 2013);               
cal.set(Calendar.DAY_OF_MONTH, 26);
cal.set(Calendar.HOUR_OF_DAY,12);
cal.set(Calendar.MINUTE,31);
//cal.add(Calendar.MINUTE, 5);
Intent alarmintent = new Intent(getApplicationContext(), AlarmReceiver.class);
alarmintent.putExtra("title","Reminder");
alarmintent.putExtra("note"," is in few minutes.");
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), HELLO_ID,
        alarmintent,PendingIntent.FLAG_UPDATE_CURRENT|  Intent.FILL_IN_DATA);
//  AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

任何人都可以帮助我。 最诚挚的问候。

1 个答案:

答案 0 :(得分:1)

您可以将调用活动的上下文保存在适配器类的私有变量中。并将其传递给intent的构造函数而不是getApplicationContext()。

private myAdapter extends PagerAdapter{
private Context mContext;
.
.
.
public myAdapter(Context context,........... ) {

super(context,  ......);
this.mContext = context;
.
.
}



//now in constructor of Intent
Intent alarmintent = new Intent(mContext, AlarmReceiver.class);
//also in pending intent

private myAdapter extends PagerAdapter{ private Context mContext; . . . public myAdapter(Context context,........... ) { super(context, ......); this.mContext = context; . . } //now in constructor of Intent Intent alarmintent = new Intent(mContext, AlarmReceiver.class); //also in pending intent