与IntentService进行Android活动通信

时间:2016-08-25 19:28:57

标签: android intentservice localbroadcastmanager

我需要在我的活动和正在运行的IntentService之间进行双向通信。

场景是这样的:应用程序可以安排运行中的警报,启动一个从Web获取某些数据并处理它的IntentService。 IntentService完成后有三种可能的情况:

  1. 应用程序处于焦点,这意味着当IntentService完成时,应用程序需要使用新数据刷新其视图。

  2. 应用程序已关闭,在IntentService完成工作后打开,因此应用程序可以访问已处理的数据

  3. 在IntentService运行时打开应用程序,在这种情况下,我需要从活动中获取一个方法来询问IntentService它是否在后台执行某些操作。
  4. For 1.我已经在我的活动中实现了一个BroadcastReceiver,它被注册到LocalBroadcastManager。当IntentService完成工作时,发送广播并且活动做出反应。这很好用

    对于2.没有什么需要做的

    对于3.我不知道该怎么做。到目前为止,我已经尝试过这个:

    活动:

    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BROADCAST_SEND_TO_SERVICE));
    

    在IntentService中

    private LocalBroadcastManager localBroadcastManager;
        private BroadcastReceiver broadcastReceiverService = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(BROADCAST_SEND_TO_SERVICE)) {
                   //does not reach this place
                   //Send back a broadcast to activity telling that it is working
                }
            }
        };
    
      @Override
        protected void onHandleIntent(Intent intent) {
    
    
            localBroadcastManager = LocalBroadcastManager.getInstance(context);
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BROADCAST_SEND_TO_SERVICE);
            localBroadcastManager.registerReceiver(broadcastReceiverService, intentFilter);
    .... //do things
    
    }
    

    我的实现问题是,IntendService是BroadcastReceiver不会触发onReceive。任何建议或者可能是一种简单的方法让Activity询问IntentService它在做什么?

    LE: 试图获得atomicboolean。 在服务中:

    public static AtomicBoolean isRunning = new AtomicBoolean(false);
    
     @Override
        protected void onHandleIntent(Intent intent) {
            isRunning.set(true);
            // do work
            // Thread.sleep(30000)
            isRunning.set(false);
    }
    

    在“活动”中,在服务运行时重新启动应用程序:

        Log(MyIntentService.isRunning.get());
    
    //this returns always false, even if the intent service is running
    

    在AndroidManifest上

     <service
                android:name=".services.MyIntentService"
                android:exported="false" />
    

0 个答案:

没有答案