服务和AlarmManager

编程入门 行业动态 更新时间:2024-10-11 11:17:41
本文介绍了服务和AlarmManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是要努力完成且严重失败的事情。

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

推荐答案

您缺少的是广播接收者

流应为

  • 启动服务。
  • 创建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
  • 请参考 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

    本文发布于:2023-11-27 13:19:28,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1638241.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:AlarmManager

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!