【问题标题】:Error while setting Notification in Android在 Android 中设置通知时出错
【发布时间】:2013-07-26 07:34:21
【问题描述】:

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

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);

谁能帮帮我。 最好的问候。

【问题讨论】:

  • 您遇到了什么错误?从 logcat 复制/粘贴。如果您收到的是NullPointerException,请尝试使用您的activity context
  • 你能不能尝试把当前上下文而不是应用程序上下文。
  • 我收到错误“创建方法 getApplicationContext()”
  • 也许这会有所帮助:stackoverflow.com/a/13523542/1276374
  • 当我在 Activity 上下文中使用相同的代码时,1)Intent alarmintent = new Intent(context, AlarmReceiver.class);2)AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);此时没有错误,但我无法设置闹钟

标签: android notifications


【解决方案1】:

您可以将调用活动的上下文保存在适配器类的私有变量中。并将其传递给意图的构造函数而不是 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

【讨论】:

  • 我使用了 Activity 上下文;这会做吗
  • 请详细说明我假设你想说你传递了你的构造函数 myAdapter(Activity context,......) 而不是你可以简单地让你的私有变量成为 私有 Activity mContext
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
相关资源
最近更新 更多