3.8 Android Toasts and Notifications

In this section we shall deal with Android notifications i.e., user gets notified on any new event arriving on device. In this section we shall study two topics namely:

  • Android Toasts
  • Android Notification

3.8.1 Android Toasts

Android Toasts are generally transient user notifications and don’t interrupt in the run of active application. They remain for few seconds on the screen and fade away. Guess what!! You have already used toast several times in previous chapters and now let us know about the other style of toasting.

Android Toast is an excellent mechanism for keeping user informed about the results of background processes without snatching their focus from current activity or forcing them to open a new activity, etc. There is a method called makeText which is a static method. It creates a standard toast window to display the alert. Toast remains on screen for approximately 2-3 seconds. The method makeText() takes three parameters:

  1. Application context: The context of application
  2. Text message: Message you want to display or message intended for alerting user
  3. Duration for toast: Minimum time for which toast should remain on screen.

Lets us go through the next code snippet and everything will be crystal clear.

Context context = getApplicationContext();
CharSequence text = "Hello Readers we are learning toasts  !";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();


                                      Code of Android Toast

It is also possible to display toast at a particular position. A standard toast is displayed at bottom of the screen positioned at center horizontally. This can be changed with the method setGravity(Gravity_constant, int, int). Gravity_constant is constant like GRAVITY.TOP, GRAVITY.LEFT, etc and integer parameters specify the offset value of x co-ordinate and y co-ordinate.

toast.setGravity(Gravity.LEFT, 0, 0);


                                       example of positioning the display of toast

We can have customized layout to display toast notification. We can specify a custom View or layout to use a more complex, or more visual, display. Using setView() on a Toast object, we can specify any View (including a layout) to display using the Toast mechanism.  Check out the following listing given below:

 

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.CUSTOMIZEDtoast,
                               (ViewGroup) findViewById(R.id.toast_layout));

TextView text = (TextView) layout.findViewById(R.id.textToast);
text.setText("Hello readers!! Welcome to your new custom toast");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

                                                  Example of custom Android Toast

We already know the simplest form of toast which has following syntax:

Toast.makeText(Context, message, duration).show():

                                                 Simplified format of Android toast

 

All these things might look confusing at first glance, don’t worry we have a solution for this. Open your IDE and create a new project. Name it as you like and I am going to name it ToastsExample. After that copy an image to the drawable folder of your project and we are good to go. Now you need to create an xml file. Select the layout folder. Right click on it. Select New-> Android xml file. Name it toast_example_layout.xml. Open this new file and type the code as shown below:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_example_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dp"
        android:src="@drawable/donald" />
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

                                                                               Custom layout file for Android toast

The graphical layout of file should be similar to the following snapshot: 

Graphical layout of custom Android toast

                                                                  Figure - Graphical layout of custom Android toast

Open your MainActvity.java file and type the code as shown in the following listing:

package com.android.tution.Toasts;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.main);
                  LayoutInflater inflater = getLayoutInflater();
                  View layout = inflater.inflate(R.layout.toast_example_layout,
                  (ViewGroup) findViewById(R.id.toast_example_layout));

                  TextView text = (TextView) layout.findViewById(R.id.text);
                  text.setText("Hello Readers !! Enjoying customized toast.. That's Donald duck");

                  Toast toast = new Toast(getApplicationContext());
                  toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                  toast.setDuration(Toast.LENGTH_LONG);
                  toast.setView(layout);
                  toast.show();
       }

}

                                                                                       MainActivity.java file of Android app

We have another xml file i.e. activity_main.xml which I have named as main.xml. Don’t worry. They are one and the same thing. Open this file and type the code as shown below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/ic_launcher"
        android:orientation="vertical" >
</LinearLayout>

                                                                        Figure - main.xml file of ToastsExample App

Graphical layout would be similar to the following snapshot:

                                                               Figure - Graphical layout of our Android App

The manifest file should appear as listed in the following listing:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.android.tution.Toasts"
     android:versionCode="1"
     android:versionName="1.0" >

     <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

     <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.android.tution.Toasts.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter> 
        </activity>
     </application>
</manifest>

                                                                         manifest file of Android app

Run your app in an emulator. The result should be similar to the following snapshot

Output of ToastsExample App displaying custom toast

Figure - Output of ToastsExample App displaying custom toast

After few seconds Donald will disappear i.e. our custom toast is toasted and then quits from the main screen. After custom toast our app will look like the following snapshot

App after custom toast exits

Figure - App after custom toast exits

Now it’s time to congratulate you…Congratulations we are done with Toasts. Now let us move to next Notification which is Notification.