Skip to content

Instantly share code, notes, and snippets.

@saggafarsyad
Last active August 5, 2019 14:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save saggafarsyad/43baf40ba40d39435864 to your computer and use it in GitHub Desktop.
Save saggafarsyad/43baf40ba40d39435864 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