将绑定Service的另一个线程中的数据发送到Activity

时间:2015-07-07 19:35:08

标签: android android-service android-service-binding

我有Activity和Service,它由来自Activity的bindService调用。在这个服务中,我使用Vk sdk在另一个线程中执行一些操作。在这里,我将json解析为我的模型并将它们添加到列表中。我的问题是如何在解析到我的活动后从另一个线程发送此列表?这是我的服务代码

public class RequestService extends Service {

private final IBinder mBinder = new RequestBinder();
private List<Item> mItems;
private String mStartFrom;
private VKRequest mVKRequest;

public class RequestBinder extends Binder {
    public RequestService getService() {
        return RequestService.this;
    }
}

@Override
public void onCreate() {
    super.onCreate();
    mItems = new ArrayList<>();
    loadNews("");
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

public void loadNews(String startFrom) {
    if (startFrom.equals("")) {
        mItems.clear();
    }
    mVKRequest = new VKRequest(Constants.METHOD_NAME, VKParameters.from(Constants.FILTERS,
            Constants.FILTER_NAMES, VKApiConst.COUNT, Constants.NEWS_COUNT, Constants.START_FROM,
            startFrom));

    // this performs in another thread
    mVKRequest.executeWithListener(new VKRequest.VKRequestListener() {

        @Override
        public void onComplete(VKResponse response) {
            super.onComplete(response);
            JSONObject result = response.json;
            try {
                mItems = ParseUtils.parse(result);
                mStartFrom = ParseUtils.getNextFrom();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });

}

public List<Item> getItems() {
    return mItems;
}

public String getStartFrom() {
    return mStartFrom;
}

}

1 个答案:

答案 0 :(得分:0)

您可以使用context.sendBroadcast(intent)。从项目中的任何类,您都可以创建一个Intent并通过广播发送此意图。

例如:

// Somewhere in your code (your service class, for example)
private void sendMessage(Context context) {
    Intent intent = new Intent("com.example.keys.MESSAGE");
    intent.putExtra("message", "Hello World!");
    // Send Broadcast to Broadcast receiver with message
    context.sendBroadcast(intent);
}

在您的活动中,您需要声明一个广播接收器:

private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
                  String message = intent.getExtras().getString("message"); // Contains "Hello World!"
                  // !!! Do something with your message !!!
         }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
        registerReceiver(mHandleMessageReceiver, new IntentFilter("com.example.keys.MESSAGE"));
}

@Override
protected void onDestroy() {
    unregisterReceiver(mHandleMessageReceiver);
}

因此,您可以从代码中的任何位置发送字符串,数字和对象。你可以拥有多个BroadcastReceiver。