This is my Service class:
public class MySrv extends Service {
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
final Context c = getApplicationContext();
Timer t = new Timer("mytimer");
TimerTask task = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(c, "Not a beautyfull day today...", Toast.LENGTH_SHORT).show();
}
};
t.schedule(task, 5000, 6000);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
The application crashes at Toast.makeText()... So what am I doing wrong?
The
TimerTask
'srun()
method doesn't execute in the UI thread, so you can't do UI-related things like creating aToast
.Investigate using a
Handler
orrunOnUiThread()
instead.Example:
The problem here is that you are trying to update the UI in the timers thread, you should use a Handler for this.
Read How to display toast inside timer?
You cannot make a Toast in another Thread, you can use a Handler to do it or use the runOnUiThread.