【问题标题】:how BroadcastReceive tell Service?BroadcastReceive如何告诉Service?
【发布时间】:2011-05-29 17:08:02
【问题描述】:

在主活动上单击按钮以启动服务

该服务将完成这些工作:

1,今天随机 10 个时间戳

2、每个时间戳到来时,都会做一个任务

现在我已经编写了函数1,当第一个时间戳到来时,我可以开始第一个任务

我的方法是通过alarmmanager为timestamp注册一个broadcastreceiver,当第一次广播触发时,再注册第二个timestamp,以此类推.....

这是我的问题: 当广播接收器被触发时,如何告诉服务注册下一个时间戳,然后完成整个工作?

或者是其他方式来实现我的服务?

提前致谢!

【问题讨论】:

    标签: android loops service handler broadcastreceiver


    【解决方案1】:

    我认为你不应该这样做。

    我可以看到您的方法中至少有两个缺点: - 警报器会太忙 - 你不能从另一个广播接收器注册一个广播接收器

    另一种更好的方法是使用 handler.postDelayed 方法:

    您的服务应该要求处理程序在几秒钟内(当您需要时)自己回来

    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {    
        //do some treatment based on the action intent
        //first action is used to compute 10 time stamps
    
        //second action is used to treat task
    
        //then use a handler to reschedule your service
        handler.postDelayed( new Runnable() {
            @Override
            public void run() {
               onStartCommand( <intent for action 2>, flags, startId);
               Log.v( LOG_TAG, "timer sending intent");
            }
        }, delayInMsToNextTask  );
    }//met
    

    因此,广播接收器没有办法。

    我忘了说您应该在清单文件中为两个意图操作注册服务。

    <service android:name="myService">
        <intent-filter>
          <action android:name="action1" />
        </intent-filter>
        <intent-filter>
          <action android:name="action2" />
        </intent-filter>
    </service>
    

    此外,添加单个操作可能会很好,但要区分 onStartCommand 应该在具有相同名称的意图中使用 extras 做什么。然后,您的服务将在清单中注册单个操作。

    下次如果你觉得你的解释不是很清楚,请发一些代码/伪代码。

    问候, 斯蒂芬

    【讨论】:

      猜你喜欢
      • 2010-11-08
      • 1970-01-01
      • 2019-09-13
      • 2014-01-05
      • 2014-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多