Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Mahmoud-Alaa-Eldeen/56a3dcb2955185f544d73e276bdafb4d to your computer and use it in GitHub Desktop.
Save Mahmoud-Alaa-Eldeen/56a3dcb2955185f544d73e276bdafb4d to your computer and use it in GitHub Desktop.
Android - Show Toast from Service
// If you Service with threads, e.g. a Chat Service
// You want to show a toast such as indicating the connection is lost or stuff when your service is running foreground
// Get main the main thread, you are only allowed to draw UI in the main thread
Handler mainHandler = new Handler(getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
// Do your stuff here related to UI, e.g. show toast
Toast.makeText(getApplicationContext(), "I'm a toast!", Toast.LENGTH_SHORT).show();
}
});
// You can use this code if you use OkHTTP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment