Android 处理程序只发送一条消息

Android handler only sends one message

我正在尝试在 android 中实现一个 REST 接口,我需要一个线程在后台发送 "I am alive" 消息到一个 IP 地址。为此,我创建了一个名为 RestPostThread 的线程,它在后台运行,同时我在 UI 线程中执行操作。

问题是,在将第一条消息发送到 RestPostThread 后,我无法退出循环程序或使用其他 IP 或其他方式向它发送不同的消息。

这里是 UI 和 RestPostThread 的代码:

public class MainActivity extends AppCompatActivity{

Handler workerThreadHandler;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    final TextView text1 = (TextView) findViewById(R.id.text1);
    final TextView text2 = (TextView) findViewById(R.id.text2);
    setSupportActionBar(toolbar);


    final RestPostThread RPT = new RestPostThread();
    RPT.start();

    while(workerThreadHandler == null ) {
        workerThreadHandler = RPT.getThreadHandler();
    }

    Button buttonStop = (Button) findViewById(R.id.buttonStop);
    buttonStop.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view) {
            try {



                workerThreadHandler.getLooper().quit();
            }catch(Exception e){
                text1.setText(e.getMessage());
                text2.setText( "Exception!");
            }

        }
    });

    Button buttonSend = (Button) findViewById(R.id.buttonSend);
    buttonSend.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view) {
            try {
                text1.setText(new RestGet().execute(editText.getText().toString()).get());
                text2.setText("everything went well!");
            }catch(Exception e){
                text1.setText(e.getMessage());
                text2.setText( "Exception!");
            }

        }
    });
}

这里是 RestPostThread 的代码:

public class RestPostThread extends Thread  {
public Handler mHandler;

@Override
public void run(){

    Looper.prepare();
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d("MYASDASDPOASODAPO", "dentro mensaje");
            while (!msg.obj.equals(null)) {
                try {
                    Thread.sleep(1000);
                    URL url = new URL(msg.obj.toString());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setDoOutput(true);
                    conn.setRequestMethod("POST");
                    String input = "<Instruction><type>put_me_in</type><room>Room 1</room></Instruction>";

                    OutputStream os = conn.getOutputStream();
                    os.write(input.getBytes());
                    os.flush();

                    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                        //  throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                    }
                    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                    String output;
                    String aux = new String();
                    while ((output = br.readLine()) != null) {
                        aux = aux + output;
                    }
                    conn.disconnect();
                    //return aux;
                } catch(MalformedURLException e) {
                    e.printStackTrace();
                    //return null;
                } catch(IOException e) {
                    e.printStackTrace();
                    //return null;
                } catch(Exception e) {
                }
            }
            Log.d("CLOSING MESSAGE", "Closing thread");
        }
    };
    Looper.loop();
}

public Handler getThreadHandler() {
    return this.mHandler;
}

查看 HandlerThread 以了解处理线程以仅处理消息的信息。你的 Handler 不应该在这样的消息上循环,它不会起作用。 Looper 的工作是处理新的、传入的 MessageRunnable 对象发送到绑定到 Looper.[=18 的 Handler =]

无论如何,您应该仔细研究一下使用 Loader 来处理 REST 类型的 API;或者,探索用于处理 REST 的第 3 方库,例如 retrofit。

我设法解决了这个问题。问题是我把所有东西都包在里面了:

while (!msg.obj.equals(null)) {}

我在这个线程和 UI 线程中实现了处理程序,现在我在两者之间来回通信,我的 RestPost线程现在看起来像这样:

public class RestPostThread extends Thread  {

public Handler mHandler,uiHandler;


public RestPostThread(Handler handler) {
    uiHandler = handler;
}

@Override
public void run(){
    Looper.prepare();
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
                try {
                    //Thread.sleep(1000);
                    URL url = new URL(msg.obj.toString());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setDoOutput(true);
                    conn.setRequestMethod("POST");
                    String input = "<Instruction><type>put_me_in</type><room>Room 1</room></Instruction>";

                    OutputStream os = conn.getOutputStream();
                    os.write(input.getBytes());
                    os.flush();

                    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                        //  throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                    }
                    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                    String output;
                    String aux = new String();
                    while ((output = br.readLine()) != null) {
                        aux = aux + output;
                    }
                    conn.disconnect();
                    Message msg2 = uiHandler.obtainMessage();
                    msg2.obj = aux;
                    uiHandler.sendMessage(msg2);
                }catch(MalformedURLException e){
                    e.printStackTrace();
                }catch(IOException e){
                    e.printStackTrace();
                }catch(Exception e){
                }
            }
    };
    Looper.loop();
}


public Handler getThreadHandler() {
    return this.mHandler;
}

}

在我的 MainActivity 中,我有这个处理程序,它允许我 "loop"(基本上只是在 RestPostThread 和 UIThread 之间来回移动)我的 Post 消息,直到我决定从 MainActivity 停止更改布尔循环:

 public Handler uiHandler = new Handler() {
    public void handleMessage(Message inputMessage) {
        Log.d("FROM UI THREAD",inputMessage.obj.toString());
        if(loop) {
            Message msg = workerThreadHandler.obtainMessage();
            String url = "http://192.168.1.224:9000/xml/android_reply";
            msg.obj = url;
            workerThreadHandler.sendMessageDelayed(msg,1000);
        }
    }
};