Wednesday, March 7, 2018

Creating Notification in Android

Notifications
A notification is an short alert  message paved in the notification panel in Android device, for ex when a SMS is received on device you see a new SMS alert in the notification panel



Using notification you can inform or alerts user about some event.


Elements of Notification
1: Content Title: title of the notification.
2: Content Text: detail of notification.
3: Icon : Icon for the notification.








Creating  Notifications

Notifications are created using NotificationCompat.Builder and NotificationManagerclass.
NotificationCompat.Builder class is used to build the notification element and NotificationManager class is used to show the notification.
Building notification
NotificationCompat.Builder mBuilder =
                                        newNotificationCompat.Builder(context)
                                        .setSmallIcon(R.drawable.icon)
                                        .setContentTitle("Notification Title”)
                                        .setContentText(“Notification detail text”);

Showing notification
// create NotificationMAnager object
NotificationManager mNotificationManager =(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId=1;
// notify using NotificationManger object
mNotificationManager.notify(notificationId, mBuilder.build());

Cancelling the notification
You need to cancel a shown notification when user has seen and clicked over it after dragging the notification panel.
to cancel the displayed notification
mNotificationManager.cancel(notificationId);

Demo Application : “Showing new SMS Notification”


What we will do : we will create a SMSReceiver class which extends BroadcastReceiver class. We register this class in manifest file as a receiver for “SMS_RECEIVED“ action. The onReceive() method of SMSReceiver class will execute when a new SMS is received on device.
In onReceive()method we extract the SMS body, and SMS Sender number from the received message. We create a notification and show that a new SMS received.
Note : Do not forget the to declare the “android.permission.RECEIVE_SMS” permission and SMSReceiver in manifest file. “android.permission.RECEIVE_SMS”  permission is required to receive SMS.



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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
   
    <!-- Permission to Receive SMS  -->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
       
        <!--  register the SMSReceiver -->
        <receiver android:name=".SmsReceiver">
            <intent-filter>
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>





SMSReceiver.java

public class SMSReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();       
        SmsMessage[] msgs = null;
        String SMSBody = "";           
        if (bundle != null)
        {
            //---retrieve the SMS message received---
           Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];           
            for (int i=0; i<msgs.length; i++)

            {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);               
                SMSBody += msgs[i].getMessageBody().toString();
            }

          // Get the Sender Phone Number
          String senderPhoneNumber=msgs[0].getOriginatingAddress();
         
        //---display the new SMS message in toast---
          Toast.makeText(context, "SMS Revived from: "+senderPhoneNumber, Toast.LENGTH_SHORT).show();
         
        /* create the notification
         * set icon, title and text
         */
          NotificationCompat.Builder mBuilder =
                      new NotificationCompat.Builder(context)
                      .setSmallIcon(R.drawable.sms)
                      .setContentTitle("New SMS Recevied from: "+senderPhoneNumber)
                      .setContentText(SMSBody);
             

        // create NotificationMAnager object
       NotificationManager mNotificationManager =
                  (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
              int notificationId=1;
              // notify using NotificationManger object
              mNotificationManager.notify(notificationId, mBuilder.build());
             

       }                        
    }
}

Android Spinner Example


Spinner


Spinner is a widget which provides a quick way to select a value from a set. A spinner presents multiple options/items to the user from which user can select one option.
For ex.  In game application when we want user to select a particular level he/she wants to play, we can use spinner to multiples levels in which can select one level.



Using Spinner


Steps to use spinner in your application

1: Defining the spinner in your .xml/layout file by using “Spinner” tag
<!—Declaring Spinner in xml -->
    <Spinner
        android:id="@+id/spinner"
        android:layout_marginTop="20dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/spinner_title"
    />

2: Create an array/arraylist of strings that will be set as the items of spinner.
String spinnerItems[]={"Level 1","Level 2","Level 3","Level 4","Level 5",};


3: Create adapter and set it with spinner
// Create adapter for spinner
ArrayAdapter  dataAdapter = newArrayAdapter(this, android.R.layout.simple_spinner_item, spinnerItems);

// attaching data adapter to spinner
mySpinnerObject.setAdapter(dataAdapter);



4: Set  clicklistener on Spinner
// set clicklisteneron Spinner
 mySpinnerObject.setOnItemSelectedListener(this);
5: override  onItemSelected() method, this method gets called by the System when an item is selected. This method receives the position parameter which signifies the index of the array/arraylist which is selected by the user.



@Override
 public voidonItemSelected(AdapterView<?> parent, View view, intposition, long id)
{
                         
// get the selected Spinner's Item
            String itemSelected = parent.getItemAtPosition(position).toString();

}

Let put all this together and develop an android application to learn how to use spinner.


Demo Application: “Working with Spinner”

What we will do: We will present a list of levels “Level 1,Level 2,Level 3,Level 4,Level 5" to the user and show the level selected by the user using Toast.


activity_main.xml

<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">


    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select the Level"
        android:layout_marginTop="20dp"
        android:textColor="#0000FF"
        android:textSize="20dp"
        android:textStyle="bold"
    />

    <!-- Spinner Element -->
    <Spinner
        android:id="@+id/spinner"
        android:layout_marginTop="20dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />

  </LinearLayout>



SpinnerMainActivity.java

public classSpinnerMainActivity extends Activity implementsOnItemSelectedListener
{
     Spinner mySpinner;
      /* create array of string of levels
     * to be set as Spinner Item
     */
    String spinnerItems[]={"Level 1","Level 2","Level 3","Level 4","Level 5",};
   
     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
         
          // get the Spinner reference
               mySpinner = (Spinner) findViewById(R.id.spinner);
       
               // set clicklistener on Spinner
               mySpinner.setOnItemSelectedListener(this);
       
              // Create adapter for spinner
          ArrayAdapter  dataAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, spinnerItems);

          // Drop down layout style - list view with radio button
                    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

          // attaching data adapter to spinner
          mySpinner.setAdapter(dataAdapter);
     }

     /* onItemSelected() method gets called by the System
      * when an item is selected
      * This method receives the position parameter
      * which signifies the index of the array
      * which is selected
      */
     @Override
        public voidonItemSelected(AdapterView<?> parent, View view, int position, long id)
        {
           
              // get the selected Spinner's Item
              String itemSelected = parent.getItemAtPosition(position).toString();

              // Showing selected spinner item
              Toast.makeText(getApplicationContext(),  itemSelected+"  Selected", Toast.LENGTH_LONG).show();
          }
      
      
       @Override
          public void onNothingSelected(AdapterViewview)
          {
              // TODOAuto-generated method stub
          }

}