我正在编写一个程序来启动定期启动服务的意图,为此我已经决定使用alarmmanager,我能够很容易地在活动中做到我想做的事情,但是我是尝试在接收器中执行此操作时出错,我无法弄清楚。
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
告诉我 ALARM_SERVICE 无法解析为变量
这是我对该接收器的完整代码:
package com.testapp21.second.activities;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class PhoneOnReceiver extends BroadcastReceiver {
private PendingIntent mAlarmSender;
@Override
public void onReceive(Context context, Intent intent) {
mAlarmSender = PendingIntent.getService(context,
0, new Intent(context, StatsCheckerService.class), 0);
// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 30*1000, mAlarmSender);
}
}
答案 0 :(得分:9)
尝试
AlarmManager am = (AlarmManager)context.getSystemService(Service.ALARM_SERVICE);
答案 1 :(得分:1)
我发现如果你在片段中就可以做到这一点
AlarmManager am = (AlarmManager)getActivity().getSystemService(Service.ALARM_SERVICE);