[英]How to stop Service using Alarm Manager at a particular time in Android?
In my app i want to stop the service in a particular time using Alarm Manager. 在我的应用程序中,我想使用Alarm Manager在特定时间停止服务。 But Alarm Manager cancel() method is not taking any time.
但是Alarm Manager cancel()方法不会花费任何时间。 So how can i stop it?
那么我该如何阻止它呢?
I wrote the code like below: 我写了如下代码:
Intent intent = new Intent(DashboardScreen.this, ServiceClass.class);
Log.d("Testing", "Intent created");
PendingIntent pi = PendingIntent.getService(DashboardScreen.this, req, intent, 0);
AlarmManager alarm_manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm_manager.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(),30*1000, pi);
Log.d("Testing", "Intent created");
Intent intent1 = new Intent(this, ServiceClass.class);
PendingIntent sender = PendingIntent.getService(this, req, intent1, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
In my opinion, you cannot stop a service using alarmmanager in a direct way. 我认为,您不能直接使用alarmmanager停止服务。 cancel() function in alarmmanager is just to remove the scheduled repeating alarm.
alarmmanager中的cancel()函数只是删除计划的重复警报。
I suggest you to call an activity which stops your service using another alarm manager when needed: 我建议您在需要时调用一个活动,该活动使用另一个警报管理器停止您的服务:
alarmmanager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+TIME_PERIOD,pendingIntent); alarmmanager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+ TIME_PERIOD,pendingIntent);
If you want to stop your service after 600 seconds, you can set TIME_PERIOD to 600*1000. 如果要在600秒后停止服务,可以将TIME_PERIOD设置为600 * 1000。 pendingIntent is for activity that stops your service.
endingIntent用于停止服务的活动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.