上下文无法解决

时间:2013-06-14 14:11:30

标签: java android alarmmanager android-alarms repeatingalarm

我正在尝试使用一种方法来安排此处描述的月度警报:

How to implement yearly and monthly repeating alarms?

但是我在线上遇到两个错误:

AlarmManager am = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);

PendingIntent sender = PendingIntent.getBroadcast(context,

声明“上下文无法解析”和“上下文无法解析为变量”

......关于如何解决这个问题的任何建议?

 public class Alarm extends Service {

    // compat to support older devices
     @Override
     public void onStart(Intent intent, int startId) {
     onStartCommand(intent, 0, startId);
     }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // your method to check if an alarm must be fired today

        PendingIntent sender = PendingIntent.getBroadcast(context,
                Integer.parseInt(Long.toString(id)), intent, 0);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(calendar.getTimeInMillis());
        calendar.add(Calendar.SECOND, 30);

        AlarmManager am = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);

        calendar.add(Calendar.MONTH, 1);

        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

        // reschedule me to check again tomorrow
        Intent serviceIntent = new Intent(Alarm.this, Alarm.class);
        PendingIntent restartServiceIntent = PendingIntent.getService(
                Alarm.this, 0, serviceIntent, 0);
        AlarmManager alarms = (AlarmManager) getSystemService(ALARM_SERVICE);
        // cancel previous alarm
        alarms.cancel(restartServiceIntent);
        // schedule alarm for today + 1 day
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);

        // schedule the alarm
        alarms.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                restartServiceIntent);
    }

    @Override
    public void onCreate() {

        // TODO Auto-generated method stub

    }

    @Override
    public IBinder onBind(Intent intent) {

        // TODO Auto-generated method stub

        return null;

    }   

    @Override
    public boolean onUnbind(Intent intent) {

        // TODO Auto-generated method stub

        return super.onUnbind(intent);

    }

}

1 个答案:

答案 0 :(得分:1)

服务是一个上下文,所以请尝试以下代码:

AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

PendingIntent sender = PendingIntent.getBroadcast(this,