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 に答える