Search code examples
androidservicetoast

android custom toast in service


I want service working after going to main menu of phone, connecting with server and if get message show custom toast. I did most of it, but i can show only text in toast. I want to make custom toast with image, I found lot of solutions how to do it in activity, but it isn't working in service.

Can someone tell me what should i change to make this code working properly?

    public class MyService extends Service {
    private Toast toast;
    private Timer timer;
    private TimerTask timerTask;
    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            showToast();
        }
    }

    private void showToast() {

        LayoutInflater inflater = (LayoutInflater)
           getSystemService(LAYOUT_INFLATER_SERVICE);
         View layout = inflater.inflate(R.layout.toast, null);
         ImageView image = (ImageView)
           layout.findViewById(R.id.image);
         image.setImageResource(R.drawable.truck); 
         TextView textView = (TextView)
           layout.findViewById(R.id.text);
         textView.setText("Some toast message");
         toast = new Toast(getApplicationContext());
         toast.setGravity(Gravity.BOTTOM, 0, 0);
         toast.setDuration(Toast.LENGTH_LONG);
         toast.setView(layout);
         toast.show();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        timer = new Timer();
        toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        clearTimerSchedule();
        initTask();
        timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000);
        return super.onStartCommand(intent, flags, startId);
    }

    private void clearTimerSchedule() {
        if(timerTask != null) {
            timerTask.cancel();
            timer.purge();
        }
    }

    private void initTask() {
        timerTask = new MyTimerTask();
    }

    @Override
    public void onDestroy() {
        clearTimerSchedule();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Solution

  • It is possible to custom Toast as our wish. It is already mentioned in the developer website itself. Check the following link http://developer.android.com/guide/topics/ui/notifiers/toasts.html