Conversion between Message and String in android? Conversion between Message and String in android? multithreading multithreading

Conversion between Message and String in android?


You don't have to overload or try to do any coversions between String and Message. What you should do, is to put that String into an object of type Message and sent it to the Handler. Then in handleMessage() extract the String from the Message.

Something like this:

// ....String message = "linkSpeed = " + linkSpeed;Message msg = Message.obtain(); // Creates an new Message instancemsg.obj = message; // Put the string into Message, into "obj" field.msg.setTarget(handler); // Set the Handlermsg.sendToTarget(); //Send the message//....

And in handleMessage():

@Overridepublic void handleMessage(Message msg) {    String message = (String) msg.obj; //Extract the string from the Message    textView.setText(message);    //....}

But besides this, the program has an issue: you won't be able to send the data to the handler because that part of the code is unreachable:

while (true) {    WifiInfo s = wifiManager.getConnectionInfo();    //..}String message = "linkSpeed = " + linkSpeed; // This line never won't be reached.

Also, don't forget to stop the Thread at some time, otherwise it will continue to run even after the app is closed.


You can attach objects - like your String - to your Message objects using a Bundle.

I have created this example:

import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;public class MainActivity extends Activity {    Handler handler = new Handler()    {        @Override        public void handleMessage(Message msg) {            Bundle bundle = msg.getData();            String text = bundle.getString("key");            // text will contain the string "your string message"        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Thread thread = new Thread()        {            @Override            public void run() {                Message message = handler.obtainMessage();                Bundle bundle = new Bundle();                bundle.putString("key", "your string message");                message.setData(bundle);                handler.sendMessage(message);            }        };        thread.start();    }}