Consider the following code. In Service.onStart()
method i have created and started a thread that should show Toast message but it is not working!
public class MyService extends Service{
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onCreate()
{
Toast.makeText(this, "My Service Created", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy()
{
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_SHORT).show();
}
@Override
public void onStart(Intent intent, int startid)
{
Toast.makeText(this, "My Service Started", Toast.LENGTH_SHORT).show();
DBIteratorThread dbThread=new DBIteratorThread();
dbThread.myService=this;
Thread t1 = new Thread(dbThread);
t1.start();
}
}
class DBIteratorThread implements Runnable
{
MyService myService;
public void run()
{
// Toast.makeText(myService, "Thread is Running", Toast.LENGTH_SHORT).show();
}
}
Steps: declare a handler in the main activity (onCreate) now create a thread from the main activity and pass the Context of that activity. now use this context in the Toast, instead of using getApplicationContext()
myActivity. runOnUiThread(new Runnable() { public void run() { Toast. makeText(myActivity, "Toast Message Text!", Toast.
Use the makeText() method, which takes the following parameters: The application Context . The text that should appear to the user. The duration that the toast should remain on the screen.
call SmartToast. cancelAll(); method when app goes into background to hide current and all pending toasts.
Do UI stuffs in main/UI thread. Try this:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
//Your UI code here
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With