我创建了一个警报,它可以工作,但问题是,在我设置的时间之后,警报在我打开应用程序的那一刻开始,有时候,当关闭时我也不打开应用程序。我有这个问题,因为很多天,有人可以帮助我吗?
这是我的代码:
ScarsdaleHome.java
public class ScarsdaleHome extends Fragment implements OnClickListener{
private AlarmManager alarmManager;
private PendingIntent pendingIntent;
public ScarsdaleHome() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.scarsdale_home_activity, container, false);
Calendar calend = Calendar.getInstance();
calend.setTimeInMillis(System.currentTimeMillis());
calend.set(Calendar.HOUR_OF_DAY, 19);
calend.set(Calendar.MINUTE, 31);
calend.set(Calendar.SECOND, 00);
Intent myIntent = new Intent(getActivity(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent,0);
alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calend.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
return rootView;
}
public static ScarsdaleHome newIstance(){
ScarsdaleHome frag= new ScarsdaleHome();
return frag;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
答案 0 :(得分:1)
您已调用setRepeating()
类的AlarmManager
方法,该方法会调度触发的重复警报,无论用户是否已打开该应用程序。如果您只想在用户打开应用时启动Service
,请使用
alarmManager.set();
或
alarmManager.setExact();
这样做。这将安排Service
仅在用户打开应用时启动。
修改强>
定义你的警报:
if(PendingIntent.getBroadcast(getActivity(), 0,
myIntent,
PendingIntent.FLAG_NO_CREATE) == null){
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent,0);
alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calend.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
如果警报已经设置,则不会重置警报。