How Can I Pass Message Via Handler In Android?
I'm learning how work handler in Android. I did Android server and socket class. I want send some message (i.e. 'New Connect') from socket to mainactivity, when somebody connect to
Solution 1:
This is a sample of a bigger project I was involved a few years ago. You will not be able to run as it is, but I think you can see how the communication between a Service and an Activity works. Feel free to ask if anything is not clear
Service
public class BluetoothService {
private final Handler mHandler;
public BluetoothService(Context context, Handler handler) {
mHandler = handler;
}
public synchronized void Connecting(...) {
...
Message MenssageToActivity = mHandler.obtainMessage(Cliente_Bluetooth.MESSAGE_HELLO);
Bundle bundle = new Bundle();
bundle.putString(BluetoothClient.DEVICE_NAME, " Gorkatan");
MensajeParaActivity.setData(bundle);
mHandler.sendMessage(MensajeParaActivity);
...
}
}
Activity
public class BluetoothClient{
public static final int MESSAGE_HELLO = 1;
public static final int MESSAGE_BYE = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
mBluetoothService = new BluetoothService(this, mHandler);
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_HELLO:
String mName = null;
mName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Hello "+ mName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_BYE:
System.out.println("Bye!")
break;
}
Here it is the whole project (which has got comments and variable names in Spanish):
Solution 2:
If you plan on sending data from a thread to your handler then use obtainMessage to create a message object.
You must also use the same instance of the handler to handleMessage and sendMessage.
Here you will find a great resource explaining how to use Handler:
Post a Comment for "How Can I Pass Message Via Handler In Android?"