Sometimes I need to show a toast message from some service or from a thread.
I make it so:
1. add private handler and public method into my Application class:
public class MyApplication extends Application {
...
private static Handler toastHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String message = msg.getData().getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
};
public static void showToast(String messageText) {
Message message = Message.obtain();
Bundle data = new Bundle();
data.putString("message", messageText);
message.setData(data);
toastHandler.sendMessage(message);
}
}
2. call my method from anywhere
public class MyService extends IntentService {
...
private void doSomething() {
...
MyApplication.showToast("Something is done");
}
}
Комментариев нет:
Отправить комментарий