1

我已经编写了一些代码来执行 httpGet,然后将 JSON 返回到主线程。有时虽然服务器已关闭,我想向主线程报告服务器已关闭但不知道如何使用处理程序正确执行此操作。

我的代码如下所示:

public class httpGet implements Runnable {

    private final Handler replyTo;
    private final String url;

    public httpGet(Handler replyTo, String url, String path, String params) {
        this.replyTo = replyTo;
        this.url = url;
    }

    @Override
    public void run() {
         try {
             // do http stuff //
         } catch (ClientProtocolException e) {
            Log.e("Uh oh", e);
            //how can I report back with the handler about the 
            //error so I can update the UI 
         }
    }
}
4

2 回答 2

2

向处理程序发送一条消息,带有一些错误代码,例如:

Message msg = new Message();
Bundle data = new Bundle();
data.putString("Error", e.toString());
msg.setData(data);
replyTo.sendMessage(msg);

在处理程序的handleMessage实现中处理此消息。

处理程序应如下所示:

Handler handler = new Handler() {
     @Override
     public void handleMessage(Message msg) {
         Bundle data = msg.getData();
         if (data != null) {
              String error = data.getString("Error");
              if (error != null) {
                  // do what you want with it
              }
         }
     }
};
于 2012-05-01T01:15:59.100 回答
1
@Override
public void run() {
     try {
         // do http stuff //
     } catch (ClientProtocolException e) {
        Log.e("Uh oh", e);
        //how can I report back with the handler about the 
        //error so I can update the UI 
        // you can use handleMessage(Message msg)
        handler.sendEmptyMessage(-1) <-- sample parameter
     }
}

从此处获取 Runnable 的消息,

Handler handler = new Handler() {
     public void handleMessage(Message msg) {
        if(msg.what == -1) {
             // report here
        }
     }
};

除了处理程序,您还可以使用 runOnUiThread,

@Override
public void run() {
     try {
         // do http stuff //
     } catch (ClientProtocolException e) {
        Log.e("Uh oh", e);
        //how can I report back with the handler about the 
        //error so I can update the UI 
        runOnUiThread(new Runnable() {
        @Override
        public void run() {
             // report here
            }
        }
     }
}
于 2012-05-01T01:42:07.767 回答