-2

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

每 5 天执行一次警报,代码是否正确?

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

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

    }

}
4

1 回答 1

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

问题出在这一行。您正在使用变量context而不声明它。使用喜欢

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

您还需要返回一个 int 从onStartCommand

利用return START_STICKY;

于 2013-06-14T19:45:31.133 回答