我正在尝试使用AlarmManager
每天(即上午11点)在特定时间运行服务。但由于某些原因,我的代码无效。
AlarmManager
public class ScheduleHelper {
/**
* @param context
* @param intent
* @param hourOfDay
*/
public static void scheduleDayly(Context context){
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 11);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Intent intent = new Intent(context, NotificationService.class);
schedule(context, intent, cal, AlarmManager.INTERVAL_DAY, 1337);
}
/**
* @param context
* @param intent
* @param calendar
*/
private static void schedule(Context context, Intent intent,
Calendar calendar, long alarmManagerTimeInterval, int requestCode) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
requestCode, intent, 0);
Toast.makeText(context, "Running in " + (System.currentTimeMillis()-calendar.getTimeInMillis()) + " ms", Toast.LENGTH_LONG).show();
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), alarmManagerTimeInterval,
pendingIntent);
}
}
NotificationService
public class NotificationService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.i("Service", "service created");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Log.i("Service", "service started");
//Todo: create notification
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("Service", "service destroyed");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Service", "service start command received");
return Service.START_STICKY;
}
}
根据LogCat,服务永远不会创建或启动(我也尝试将日历设置为过去5分钟,结果相同)
你能告诉我我做错了什么吗?不幸的是,在这里阅读关于同一主题的几个问题无助于解决问题。
答案 0 :(得分:0)
要使用具有待定意图的服务,请使用:
PendingIntent pendingIntent = PendingIntent.getService(context,
requestCode, intent, 0);
这是您想要从Pending Intent广播的内容。
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
requestCode, intent, 0);