向Android中的处理程序发送错误

时间:2012-05-01 01:11:49

标签: android runnable

我编写了一些代码来执行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 
         }
    }
}

2 个答案:

答案 0 :(得分: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
              }
         }
     }
};

答案 1 :(得分: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
            }
        }
     }
}