对于AlarmReceiver类型,方法getApplicationContext()未定义

时间:2014-03-29 13:17:29

标签: android broadcastreceiver alarmmanager

在我的mainActivity应用程序中,我创建了一个警报管理器对象

我正在调用一个Broadcastreceiver类AlarmReceiver。

在该类中,我正在初始化数据库对象,但它显示错误

  

方法getApplicationContext()未定义类型   AlarmReceiver"

我怎样才能克服这一点。

AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver {
     @Override
     public void onReceive(Context arg0, Intent arg1) {
       Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();
       DatabaseHandler1 db = new DatabaseHandler1(getApplicationContext());
     }
}

在mainActivity中

Date dat  = new Date();//initializes to now
Calendar cal_alarm = Calendar.getInstance();
Calendar cal_now = Calendar.getInstance();
cal_now.setTime(dat);
cal_alarm.setTime(dat);

cal_alarm.set(Calendar.HOUR_OF_DAY, 8);
cal_alarm.set(Calendar.MINUTE, 55);
cal_alarm.set(Calendar.SECOND, 0);
cal_alarm.set(Calendar.MILLISECOND, 0);

if(cal_alarm.before(cal_now)){  //if its in the past increment
  cal_alarm.add(Calendar.DATE,1);
}

Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), pendingIntent);

3 个答案:

答案 0 :(得分:0)

查看onReceive()

的方法
public void onReceive(Context arg0, Intent arg1)

您将上下文作为参数传递。你应该使用那个上下文。

答案 1 :(得分:0)

只需使用arg0。您无需使用getApplicationContext()

答案 2 :(得分:0)

public class AlarmReceiver extends BroadcastReceiver {


     @Override
     public void onReceive(Context arg0, Intent arg1) {
         Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();
            DatabaseHandler1 db = new DatabaseHandler1(arg0);


     }
}