在我的项目中,我的课程延伸Fragment
。我无法理解为什么AlarmManager
无效。在logcat中它显示NullPointerException
:
Intent myIntent = new Intent(context, AppService.class);
pendingIntent = PendingIntent.getService(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10*1000, pendingIntent);
Toast.makeText(getActivity().getApplicationContext(), "Start Alarm", Toast.LENGTH_LONG).show();
答案 0 :(得分:1)
一个很好的链接是@ Scheduling Alarms。网页上的代码段:
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
...
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() +
60 * 1000, alarmIntent);
请注意,它为getSystemService方法使用了Context.ALARM_SERVICE。