Try using the this
from your Activity instead of using getApplicationContext():
Toast.makeText(
YourActivity.this,
"This is toast message from inside onTick of the CountDownTimer inside the Service",
Toast.LENGTH_LONG).show();
Pregunta
I am trying to display a Toast message from inside onTick() function of a CountDownTimer class. This class is running inside a service.
Simple doing Toast.maketext("tag", "toast message") - crashes the application.
So I tried a handler - With the handler, app does not crash but I do not see a toast message either. Any help on what is wrong will be helpful.
I am sure that my countdown timer is running properly and onTick is being called - i have added LogCat statements to confirm that.
public class MyServicelockCountdownTimer extends CountDownTimer {
public FBServicelockCountdownTimer(long millisInFuture,
long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
}
@Override
public void onTick(long millisUntilFinished) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(
getApplicationContext(),
"This is toast message from inside onTick of the CountDownTimer inside the Service",
Toast.LENGTH_LONG).show();
}
});
} else {
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
}
Solución
Try using the this
from your Activity instead of using getApplicationContext():
Toast.makeText(
YourActivity.this,
"This is toast message from inside onTick of the CountDownTimer inside the Service",
Toast.LENGTH_LONG).show();
Otros consejos
Try using getMainLooper() method of Looper class which -
Returns the application's main looper, which lives in the main thread of the application. // from android docs.
And you should also consider binding Activites to services in order to handle UI updates.
Check this link as well for more details.
public abstract void onReceive (Context context, Intent intent)
in onReceive you will context
Call getApplicationContext() on the Context supplied to you in onReceive(), just as you would call getApplicationContext() on an Activity.