简体   繁体   English

在指定时间内运行Broadcastreceiver

[英]Run Broadcastreceiver for specified time

I am new to android, I want to run a task only for a specific duration, how can I do this? 我是android新手,我只想在特定时间段内运行任务,该怎么办? I tried using broadcast receiver and AlarmManager but the broadcastreceiver continuously runs even after specified time. 我尝试使用广播接收器和AlarmManager但是即使在指定时间后,广播接收器AlarmManager连续运行。

long timetorun= calendarcurrent.getTimeInMillis() - calendar.getTimeInMillis();
Intent c = new Intent(getApplicationContext(),
Phonecallreceiver.class); 
pintent = PendingIntent.getBroadcast(getApplicationContext(), 0, c, 0);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, timetorun, pintent);

You can stop it by canceling the alarm, using the same PendingIntent like the below: 您可以使用以下相同的PendingIntent通过取消警报来停止它:

Intent c = new Intent(getApplicationContext(), Phonecallreceiver.class); 
pintent = PendingIntent.getBroadcast(getApplicationContext(), 0, c, 0);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE); 
alarm .cancel(pintent);

Do not forget to make sure that the PendingIntent is not NULL. 不要忘记确保PendingIntent不为NULL。 Hope that I helped you. 希望我能帮到您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM