打开应用程序时,警报会持续触发

时间:2015-03-18 08:33:30

标签: android android-alarms

我创建了一个警报,它可以工作,但问题是,在我设置的时间之后,警报在我打开应用程序的那一刻开始,有时候,当关闭时我也不打开应用程序。我有这个问题,因为很多天,有人可以帮助我吗?

这是我的代码:

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

    }   
}

1 个答案:

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

}

如果警报已经设置,则不会重置警报。