本文介绍了服务和AlarmManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
启动服务。 创建BroadCast收件人 在服务中执行任务 设置警报以触发BroadCast Recievr(在接收到广播接收者后,再次启动Service。) 调用StopSelf,它将停止您的服务,可以从广播接收方重新启动
Start Service.
Create a BroadCast Reciever
Perform Task in service
Set Alarm to Trigger BroadCast Recievr( on Reception of bradcast reciever start Service again.)
Call StopSelf it will stop your service which can be restarted from broadcast recievr
这是要努力完成且严重失败的事情。
here is what am trying to accomplish and badly failing at it.
我需要:
-启动服务
-执行一些任务
-设置AlarmManager在设置的时间段后再次启动服务时间
-set AlarmManager to start the service again after a set period of time
-停止服务
我遇到的问题是该服务正在重新开始几乎立即停止。我只想在警报响起后启动该服务。
the problem I'm having is that the service is being re-started almost immediately it is being stopped. All I want is that the service should start after the alarm goes off..
这是代码:-
Intent intent = new Intent(ThisService.this, ThisService.class); PendingIntent pendingIntent = PendingIntent.getService(ThisService.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); alarmManager.cancel(pendingIntent); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, getUpdateTime(), getUpdateTime(), pendingIntent); stopSelf();推荐答案
您缺少的是广播接收者
流应为
请参考 www.vogella/articles/AndroidBroadcastReceiver/article.html
//-----Set the alarm to trigger the broadcast reciver----------------------------- Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234324243, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent); Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show(); //---------------Call StopSelf here-------------------- //---------------------------------------------------------------------------------- public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //-----------write code to start the service-------------------------- } }更多推荐
服务和AlarmManager
发布评论