【问题标题】:Communication between Android service and activity using listener使用监听器在 Android 服务和活动之间进行通信
【发布时间】:2013-09-07 15:27:49
【问题描述】:

我看到的大多数活动和服务之间的通信示例都使用广播接收器。我的问题是我可以用普通听众替换广播接收器吗?然后我不必担心将我的 Web 服务响应编组到 Intent/Bundle 类中。这种方法有什么问题吗?有什么比使用广播接收器更不利的吗? AddListener 将在 Activity 的 onCreate 方法中调用,而 RemoveListener 将在 Activity 的 onDestroy 方法中调用。

package com.example.test;

import java.util.ArrayList;
import java.util.List;

import android.app.IntentService;
import android.content.Intent;

public class AsyncService extends IntentService
{
    static List<WebServiceListener> listeners = new ArrayList<WebServiceListener>();

    public static void addListener(WebServiceListener listener)
    {
        listeners.add(listener);
    }

    public static void removeListener(WebServiceListener listener)
    {
        listeners.remove(listener);
    }

    public AsyncService(String name)
    {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        try
        {
            Thread.sleep(5000); //simulate calling webservice
        }
        catch (Exception e)
        {
            //
        }

        WebServiceResponse response = new WebServiceResponse();
        response.status = "SUCCESS";

        for (WebServiceListener listener : listeners)
        {
            listener.onReceiveResult(response);
        }
    }
}

【问题讨论】:

    标签: android service android-activity communication


    【解决方案1】:

    如果是本地服务,是的,你可以这样做

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-16
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      相关资源
      最近更新 更多