Отправка ошибки обработчику в Android

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 
         }
    }
}
Теги:
runnable

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
              }
         }
     }
};
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
            }
        }
     }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню