I have a doubt in the usage of handlers in the following scenario
I have a an activity class as follows:
public class MyActivity extends Activity {
...
...
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
...
}
}
and a BluetoothClientConnection class as follows
public class BTClientConnection extends Thread {
public void run {
...
}
}
Now I want to update the UI using handlers. How should I be doing it? Should I create a public handler variable and refer to it directly from my BluetoothClientConnection code? Is this the best practice as I would be directly coupling with the MyActivity class.
From Gennadii Saprykin answer should the final code be
public class MyActivity extends Activity {
...
private ActivityHandler activityhandler = new ActivityHandler();
static class ActivityHandler extends Handler {
@Override
public void handleMessage(Message msg) {
}
...
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
...
BTClientConnection btClientConnection = new BTClientConnection(..);
btClientConnection.start();
}
}
public class BTClientConnection extends Thread {
private static final Handler UI_HANDLER = new Handler(Looper.getMainLooper());
public void run {
Message message = new Message();
UI_HANDLER.sendMessage(message);
}
}