服务和AlarmManager [英] Service and AlarmManager

查看:102
本文介绍了服务和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();


推荐答案

您缺少的是广播接收者

流应为


  1. 启动服务。

  2. 创建BroadCast收件人

  3. 在服务中执行任务

  4. 设置警报以触发BroadCast Recievr(在接收到广播接收者后,再次启动Service。)

  5. 调用StopSelf,它将停止您的服务,可以从广播接收方重新启动

  1. Start Service.
  2. Create a BroadCast Reciever
  3. Perform Task in service
  4. Set Alarm to Trigger BroadCast Recievr( on Reception of bradcast reciever start Service again.)
  5. Call StopSelf it will stop your service which can be restarted from broadcast recievr

请参考 http://www.vogella.com/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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆