上下文无法解析为变量 - 遵循5天的警报示例

时间:2013-06-14 19:44:07

标签: java android alarmmanager android-alarms

我正在尝试使用以下SO示例中的代码设置重复出现的警报示例:

Implementing an alarm every 5 days, code correct?

但是我收到一条错误,指出“无法将上下文解析为变量”:

PendingIntent pi = PendingIntent.getBroadcast(context, 0, Aintent, 0);

有什么建议吗?

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) {
        // method to check if an alarm must be fired today

        String alarm = Context.ALARM_SERVICE;
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
         calendar = Calendar.getInstance();
         calendar.set(Calendar.DAY_OF_WEEK, 5);
         calendar.set(Calendar.HOUR_OF_DAY, 23);
         calendar.set(Calendar.MINUTE, 0);
         calendar.set(Calendar.SECOND, 0);

         Intent Aintent = new Intent("REFRESH_THIS");

         PendingIntent pi = PendingIntent.getBroadcast(context, 0, Aintent, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, pi);


        // reschedule 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 :(得分:2)

PendingIntent pi = PendingIntent.getBroadcast(context, 0, Aintent, 0);

问题出在这一行。您正在使用变量context而未声明它。使用像

PendingIntent pi = PendingIntent.getBroadcast(this, 0, Aintent, 0);

您还需要从onStartCommand

返回一个int

使用return START_STICKY;