Cloud208 Blog

Android Custom Toast from a Service

In Android, toasts are simple notifications that pop-up on the screen and go away after few seconds. They are particularly handy if a background service wants to inform user about some event like that download has completed, file has been saved or something similar. Usually toasts are just plain text messages, but it also possible to use custom layouts for them, and add some visual buzz.

While searching the web, I have found many examples how to use simple toasts from a service, and many examples how to use custom toasts from an activity, but I spent some time trying to find out how to display custom toast from a service. The problem is that services are not intended to have user interface, and they do not have the same infrastructure for loading views like activities have.

Anyway, solution turned out to be a rather simple one once I have found it. The trick is to call inflate without second parameter (by giving it null). Here is the code snippet that would fire custom toast from a service:

 LayoutInflater layoutInflater = (LayoutInflater)
   getSystemService(LAYOUT_INFLATER_SERVICE);
 View layout = inflater.inflate(R.layout.toast_layout, null);
 ImageView image = (ImageView)
   layout.findViewById(R.id.image);
 image.setImageResource(R.drawable.imageres); 
 TextView textView = (TextView)
   layout.findViewById(R.id.textbox);
 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();
Posted by rush at 1 September 2010, 6:49 am with tags Android link