Monday, August 10, 2015

Android Concepts

Android Concepts

Android drag/drop framework allows your users to move data from one View to another View in the current layout using a graphical drag and drop gesture. As of API 11 drag and drop of view onto other views or view groups is supported.The framework includes following three important components to support drag & drop functionality −
  • Drag event class:
  • Drag listeners:
  • Helper methods and classes:

The Drag/Drop Process

There are basically four steps or states in the drag and drop process:
  • Started − This event occurs when you start dragging an item in a layout, your application calls startDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow.
    The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device.
    Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout.
    To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED.
  • Continuing − The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object's appearance in response to the event or can react by highlighting its View.
    The drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View.
  • Dropped − The user releases the dragged item within the bounding box of a View. The system sends the View object's listener a drag event with action type ACTION_DROP.
  • Ended − Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over.

The DragEvent Class

The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Constants and important methods which we use during Drag/Drop process.

Constants

Following are all constants integers available as a part of DragEvent class.
Sr.No.Constants & Description
1ACTION_DRAG_STARTED
Signals the start of a drag and drop operation.
2ACTION_DRAG_ENTERED
Signals to a View that the drag point has entered the bounding box of the View.
3ACTION_DRAG_LOCATION
Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object's bounding box.
4ACTION_DRAG_EXITED
Signals that the user has moved the drag shadow outside the bounding box of the View.
5ACTION_DROP
Signals to a View that the user has released the drag shadow, and the drag point is within the bounding box of the View.
6ACTION_DRAG_ENDED
Signals to a View that the drag and drop operation has concluded.

Methods

Following are few important and most frequently used methods available as a part of DragEvent class.
Sr.No.Constants & Description
1int getAction()
Inspect the action value of this event..
2ClipData getClipData()
Returns the ClipData object sent to the system as part of the call to startDrag().
3ClipDescription getClipDescription()
Returns the ClipDescription object contained in the ClipData.
4boolean getResult()
Returns an indication of the result of the drag and drop operation.
5float getX()
Gets the X coordinate of the drag point.
6float getY()
Gets the Y coordinate of the drag point.
7String toString()
Returns a string representation of this DragEvent object.

Listening for Drag Event

If you want any of your views within a Layout should respond Drag event then your view either implements View.OnDragListener or setup onDragEvent(DragEvent) callback method. When the system calls the method or listener, it passes to them a DragEvent object explained above. You can have both a listener and a callback method for View object. If this occurs, the system first calls the listener and then defined callback as long as listener returns true.
The combination of the onDragEvent(DragEvent) method and View.OnDragListener is analogous to the combination of the onTouchEvent() and View.OnTouchListener used with touch events in old versions of Android.

Starting a Drag Event

You start with creating a ClipData and ClipData.Item for the data being moved. As part of the ClipData object, supply metadata that is stored in a ClipDescription object within the ClipData. For a drag and drop operation that does not represent data movement, you may want to use null instead of an actual object.
Next either you can extend extend View.DragShadowBuilder to create a drag shadow for dragging the view or simply you can use View.DragShadowBuilder(View) to create a default drag shadow that's the same size as the View argument passed to it, with the touch point centered in the drag shadow.

Example

Following example shows the functionality of a simple Drag & Drop usingView.setOnLongClickListener(), View.setOnTouchListener()andView.OnDragEventListener().
StepDescription
1You will use Android studio IDE to create an Android application and name it asMy Application under a package com.example.saira_000.myapplication. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file and add the code to define event listeners as well as a call back methods for the logo image used in the example.
3Copy image abc.png in res/drawable-* folders. You can use images with different resolution in case you want to provide them for different devices.
4Modify layout XML file res/layout/activity_main.xml to define default view of the logo images.
5Run the application to launch Android emulator and verify the result of the changes done in the application.
Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.saira_000.myapplication;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;


public class MainActivity extends Activity {
   ImageView img;
   String msg;
   private android.widget.RelativeLayout.LayoutParams layoutParams;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      img=(ImageView)findViewById(R.id.imageView);
      
      img.setOnLongClickListener(new View.OnLongClickListener() {
         @Override
         public boolean onLongClick(View v) {
            ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());
            String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
            
            ClipData dragData = new ClipData(v.getTag().toString(),mimeTypes, item);
            View.DragShadowBuilder myShadow = new View.DragShadowBuilder(img);
            
            v.startDrag(dragData,myShadow,null,0);
            return true;
         }
      });
      
      img.setOnDragListener(new View.OnDragListener() {
         @Override
         public boolean onDrag(View v, DragEvent event) {
            switch(event.getAction())
            {
               case DragEvent.ACTION_DRAG_STARTED:
               layoutParams = (RelativeLayout.LayoutParams)v.getLayoutParams();
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_STARTED");
               
               // Do nothing
               break;
               
               case DragEvent.ACTION_DRAG_ENTERED:
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENTERED");
               int x_cord = (int) event.getX();
               int y_cord = (int) event.getY();
               break;
               
               case DragEvent.ACTION_DRAG_EXITED :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
               x_cord = (int) event.getX();
               y_cord = (int) event.getY();
               layoutParams.leftMargin = x_cord;
               layoutParams.topMargin = y_cord;
               v.setLayoutParams(layoutParams);
               break;
               
               case DragEvent.ACTION_DRAG_LOCATION  :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");
               x_cord = (int) event.getX();
               y_cord = (int) event.getY();
               break;
               
               case DragEvent.ACTION_DRAG_ENDED   :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");
               
               // Do nothing
               break;
               
               case DragEvent.ACTION_DROP:
               Log.d(msg, "ACTION_DROP event");
               
               // Do nothing
               break;
               default: break;
            }
            return true;
         }
      });
      
      img.setOnTouchListener(new View.OnTouchListener() {
         @Override
         public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
               ClipData data = ClipData.newPlainText("", "");
               View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(img);
               
               img.startDrag(data, shadowBuilder, img, 0);
               img.setVisibility(View.INVISIBLE);
               return true;
            }
            else
            {
               return false;
            }
         }
      });
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" 
   android:layout_width="match_parent"
   android:layout_height="match_parent" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" 
   tools:context=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Drag and Drop Example"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="30dp"
      android:textColor="#ff14be3c" />>
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_alignLeft="@+id/textView2"
      android:layout_alignStart="@+id/textView2" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">My Application</string>
   <string name="action_settings">Settings</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.guidemo"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-sdk
      android:minSdkVersion="11"
      android:targetSdkVersion="22" />
      
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.guidemo.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>
Let's try to run your My Application application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Android Drag and Drop
Now do long click on the displayed TutorialsPoint logo and you will see that logo image moves a little after 1 seconds long click from its place, its the time when you should start dragging the image. You can drag it around the screen and drop it at a new location.
Android Drop to New Location
notification is a message you can display to the user outside of your application's normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time.
Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persistent which means alert flashes on the screen for a few seconds and then disappears.
Android Notification Bar
To see the details of the notification, you will have to select the icon which will display notification drawer having detail about the notification. While working with emulator with virtual device, you will have to click and drag down the status bar to expand it which will give you detail as follows. This will be just 64 dp tall and called normal view.
Android Notification Detail
Above expanded form can have a Big View which will have additional detail about the notification. You can add upto six additional lines in the notification. The following screen shot shows such notification.

Create and Send Notifications

You have simple way to create a notification. Follow the following steps in your application to create a notification −

Step 1 - Create Notification Builder

As a first step is to create a notification builder using NotificationCompat.Builder.build(). You will use Notification Builder to set various Notification properties like its small and large icons, title, priority etc.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

Step 2 - Setting Notification Properties

Once you have Builder object, you can set its Notification properties using Builder object as per your requirement. But this is mandatory to set at least following −
  • A small icon, set by setSmallIcon()
  • A title, set by setContentTitle()
  • Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
You have plenty of optional properties which you can set for your notification. To learn more about them, see the reference documentation for NotificationCompat.Builder.

Step 3 - Attach Actions

This is an optional part and required if you want to attach an action with the notification. An action allows users to go directly from the notification to an Activity in your application, where they can look at one or more events or do further work.
The action is defined by a PendingIntent containing an Intent that starts an Activity in your application. To associate the PendingIntent with a gesture, call the appropriate method ofNotificationCompat.Builder. For example, if you want to start Activity when the user clicks the notification text in the notification drawer, you add the PendingIntent by callingsetContentIntent().
A PendingIntent object helps you to perform an action on your applications behalf, often at a later time, without caring of whether or not your application is running.
We take help of stack builder object which will contain an artificial back stack for the started Activity. This ensures that navigating backward from the Activity leads out of your application to the Home screen.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);

// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

Step 4 - Issue the notification

Finally, you pass the Notification object to the system by calling NotificationManager.notify() to send your notification. Make sure you call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());

The NotificationCompat.Builder Class

The NotificationCompat.Builder class allows easier control over all the flags, as well as help constructing the typical notification layouts. Following are few important and most frequently used methods available as a part of NotificationCompat.Builder class.
Sr.No.Constants & Description
1Notification build()
Combine all of the options that have been set and return a new Notification object.
2NotificationCompat.Builder setAutoCancel (boolean autoCancel)
Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel.
3NotificationCompat.Builder setContent (RemoteViews views)
Supply a custom RemoteViews to use instead of the standard one.
4NotificationCompat.Builder setContentInfo (CharSequence info)
Set the large text at the right-hand side of the notification.
5NotificationCompat.Builder setContentIntent (PendingIntent intent)
Supply a PendingIntent to send when the notification is clicked.
6NotificationCompat.Builder setContentText (CharSequence text)
Set the text (second row) of the notification, in a standard notification.
7NotificationCompat.Builder setContentTitle (CharSequence title)
Set the text (first row) of the notification, in a standard notification.
8NotificationCompat.Builder setDefaults (int defaults)
Set the default notification options that will be used.
9NotificationCompat.Builder setLargeIcon (Bitmap icon)
Set the large icon that is shown in the ticker and notification.
10NotificationCompat.Builder setNumber (int number)
Set the large number at the right-hand side of the notification.
11NotificationCompat.Builder setOngoing (boolean ongoing)
Set whether this is an ongoing notification.
12NotificationCompat.Builder setSmallIcon (int icon)
Set the small icon to use in the notification layouts.
13NotificationCompat.Builder setStyle (NotificationCompat.Style style)
Add a rich notification style to be applied at build time.
14NotificationCompat.Builder setTicker (CharSequence tickerText)
Set the text that is displayed in the status bar when the notification first arrives.
15NotificationCompat.Builder setVibrate (long[] pattern)
Set the vibration pattern to use.
16NotificationCompat.Builder setWhen (long when)
Set the time that the event occurred. Notifications in the panel are sorted by this time.

Example

Following example shows the functionality of a Android notification using aNotificationCompat.Builder Class which has been introduced in Android 4.1.
StepDescription
1You will use Android studio IDE to create an Android application and name it astutorialspoint under a package com.example.notificationdemo. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file and add the code to notify(""), if user click on the button,it will call android notification service.
3Create a new Java file src/NotificationView.java, which will be used to display new layout as a part of new activity which will be started when user will click any of the notifications
4Modify layout XML file res/layout/activity_main.xml to add Notification button in relative layout.
5Create a new layout XML file res/layout/notification.xml. This will be used as layout file for new activity which will start when user will click any of the notifications.
6No need to change default string constants. Android studio takes care of default string constants
7Run the application to launch Android emulator and verify the result of the changes done in the application.
Following is the content of the modified main activity filesrc/com.example.notificationdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.notificationdemo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {
   Button b1;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      b1=(Button)findViewById(R.id.button);
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Notify("You've received new message");
         }
      });
   }
   private void Notify(String notificationTitle, String notificationMessage){
      NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      @SuppressWarnings("deprecation")
      
      Notification notification = new Notification(R.drawable.abc,"New Message", System.currentTimeMillis());
      Intent notificationIntent = new Intent(this,NotificationView.class);
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0);
      
      notification.setLatestEventInfo(MainActivity.this, notificationTitle,notificationMessage, pendingIntent);
      notificationManager.notify(9999, notification);
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}
Following will be the content of res/layout/notification.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent" >
   
   <TextView
      android:layout_width="fill_parent"
      android:layout_height="400dp"
      android:text="Hi, Your Detailed notification view goes here...." />
</LinearLayout>
Following is the content of the modified main activity filesrc/com.example.notificationdemo/NotificationView.java.
package com.example.notificationdemo;

import android.os.Bundle;
import android.app.Activity;

public class NotificationView extends Activity{
   @Override
   public void onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      setContentView(R.layout.notification);
   }
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context="MainActivity">
   
   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Notification Example"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_below="@+id/textView1"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="48dp" />
      
   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="42dp" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Notification"
      android:id="@+id/button"
      android:layout_marginTop="62dp"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true" />
      
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="action_settings">Settings</string>
   <string name="app_name">tutorialspoint </string>  
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.notificationdemo"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.notificationdemo.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>
      
      <activity android:name=".NotificationView"
         android:label="Details of notification"
         android:parentActivityName=".MainActivity">
         <meta-data
         android:name="android.support.PARENT_ACTIVITY"
         android:value=".MainActivity"/>
      </activity>
      
   </application>
</manifest>
Let's try to run your tutorialspoint application. I assume you had created your AVD while doing environment set-up. To run the APP from Android Studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Android Notification Start
Now click button, you will see at the top a message "New Message Alert!" will display momentarily and after that you will have following screen having a small icon at the top left corner.
Now lets expand the view, long click on the small icon, after a second it will display date information and this is the time when you should drag status bar down without releasing mouse. You will see status bar will expand and you will get following screen −
Android Notification Expanded

Big View Notification

The following code snippet demonstrates how to alter the notification created in the previous snippet to use the Inbox big view style. I'm going to update displayNotification() modification method to show this functionality −
protected void displayNotification() {
   Log.i("Start", "notification");

   /* Invoking the default notification service */
   NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(this);
   
   mBuilder.setContentTitle("New Message");
   mBuilder.setContentText("You've received new message.");
   mBuilder.setTicker("New Message Alert!");
   mBuilder.setSmallIcon(R.drawable.woman);
   
   /* Increase notification number every time a new notification arrives */
   mBuilder.setNumber(++numMessages);
   
   /* Add Big View Specific Configuration */
   NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
   
   String[] events = new String[6];
   events[0] = new String("This is first line....");
   events[1] = new String("This is second line...");
   events[2] = new String("This is third line...");
   events[3] = new String("This is 4th line...");
   events[4] = new String("This is 5th line...");
   events[5] = new String("This is 6th line...");
   
   // Sets a title for the Inbox style big view
   inboxStyle.setBigContentTitle("Big Title Details:");
   
   // Moves events into the big view
   for (int i=0; i < events.length; i++) {
      inboxStyle.addLine(events[i]);
   }
   
   mBuilder.setStyle(inboxStyle);
   
   /* Creates an explicit intent for an Activity in your app */
   Intent resultIntent = new Intent(this, NotificationView.class);
   
   TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
   stackBuilder.addParentStack(NotificationView.class);

   /* Adds the Intent that starts the Activity to the top of the stack */
   stackBuilder.addNextIntent(resultIntent);
   PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
   
   mBuilder.setContentIntent(resultPendingIntent);
   mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
   
   /* notificationID allows you to update the notification later on. */
   mNotificationManager.notify(notificationID, mBuilder.build());
}
Now if you will try to run your application then you will find following result in expanded form of the view −
Android Notification Big View
Android location APIs make it easy for you to build location-aware applications, without needing to focus on the details of the underlying location technology.
This becomes possible with the help of Google Play services, which facilitates adding location awareness to your app with automated location tracking, geofencing, and activity recognition.
This tutorial shows you how to use Location Services in your APP to get the current location, get periodic location updates, look up addresses etc.

The Location Object

The Location object represents a geographic location which can consist of a latitude, longitude, time stamp, and other information such as bearing, altitude and velocity. There are following important methods which you can use with Location object to get location specific information:
Sr.No.Method & Description
1float distanceTo(Location dest)
Returns the approximate distance in meters between this location and the given location.
2float getAccuracy()
Get the estimated accuracy of this location, in meters.
3double getAltitude()
Get the altitude if available, in meters above sea level.
4float getBearing()
Get the bearing, in degrees.
5double getLatitude()
Get the latitude, in degrees.
6double getLongitude()
Get the longitude, in degrees.
7float getSpeed()
Get the speed if it is available, in meters/second over ground.
8boolean hasAccuracy()
True if this location has an accuracy.
9boolean hasAltitude()
True if this location has an altitude.
10boolean hasBearing()
True if this location has a bearing.
11boolean hasSpeed()
True if this location has a speed.
12void reset()
Clears the contents of the location.
13void setAccuracy(float accuracy)
Set the estimated accuracy of this location, meters.
14void setAltitude(double altitude)
Set the altitude, in meters above sea level.
15void setBearing(float bearing)
Set the bearing, in degrees.
16void setLatitude(double latitude)
Set the latitude, in degrees.
17void setLongitude(double longitude)
Set the longitude, in degrees.
18void setSpeed(float speed)
Set the speed, in meters/second over ground.
19String toString()
Returns a string containing a concise, human-readable description of this object.

Get the Current Location

To get the current location, create a location client which is LocationClient object, connect it to Location Services using connect() method, and then call its getLastLocation() method. This method returns the most recent location in the form of Location object that contains latitude and longitude coordinates and other information as explained above. To have location based functionality in your activity, you will have to implement two interfaces −
  • GooglePlayServicesClient.ConnectionCallbacks
  • GooglePlayServicesClient.OnConnectionFailedListener
These interfaces provide following important callback methods, which you need to implement in your activity class −
Sr.No.Callback Methods & Description
1abstract void onConnected(Bundle connectionHint)
This callback method is called when location service is connected to the location client successfully. You will use connect() method to connect to the location client.
2abstract void onDisconnected()
This callback method is called when the client is disconnected. You will usedisconnect() method to disconnect from the location client.
3abstract void onConnectionFailed(ConnectionResult result)
This callback method is called when there was an error connecting the client to the service.
You should create the location client in onCreate() method of your activity class, then connect it in onStart(), so that Location Services maintains the current location while your activity is fully visible. You should disconnect the client in onStop() method, so that when your app is not visible, Location Services is not maintaining the current location. This helps in saving battery power up-to a large extent.

Get the Updated Location

If you are willing to have location updates, then apart from above mentioned interfaces, you will need to implement LocationListener interface as well. This interface provide following callback method, which you need to implement in your activity class −
Sr.No.Callback Method & Description
1abstract void onLocationChanged(Location location)
This callback method is used for receiving notifications from the LocationClient when the location has changed.

Location Quality of Service

The LocationRequest object is used to request a quality of service (QoS) for location updates from the LocationClient. There are following useful setter methods which you can use to handle QoS. There are equivalent getter methods available which you can check in Android official documentation.
Sr.No.Method & Description
1setExpirationDuration(long millis)
Set the duration of this request, in milliseconds.
2setExpirationTime(long millis)
Set the request expiration time, in millisecond since boot.
3setFastestInterval(long millis)
Explicitly set the fastest interval for location updates, in milliseconds.
4setInterval(long millis)
Set the desired interval for active location updates, in milliseconds.
5setNumUpdates(int numUpdates)
Set the number of location updates.
6setPriority(int priority)
Set the priority of the request.
Now for example, if your application wants high accuracy location it should create a location request with setPriority(int) set to PRIORITY_HIGH_ACCURACY andsetInterval(long) to 5 seconds. You can also use bigger interval and/or other priorities like PRIORITY_LOW_POWER for to request "city" level accuracy or PRIORITY_BALANCED_POWER_ACCURACY for "block" level accuracy.
Activities should strongly consider removing all location request when entering the background (for example at onPause()), or at least swap the request to a larger interval and lower quality to save power consumption.

Displaying a Location Address

Once you have Location object, you can use Geocoder.getFromLocation() method to get an address for a given latitude and longitude. This method is synchronous, and may take a long time to do its work, so you should call the method from the doInBackground()method of an AsyncTask class.
The AsyncTask must be subclassed to be used and the subclass will overridedoInBackground(Params...) method to perform a task in the background andonPostExecute(Result) method is invoked on the UI thread after the background computation finishes and at the time to display the result. There is one more important method available in AyncTask which is execute(Params... params), this method executes the task with the specified parameters.
Check following example to have better understanding on how we use AynchTask in any Android application to get work done in the background without interfering main task.

Example

Following example shows you in practical how to to use Location Services in your app to get the current location and its equivalent addresses etc.
To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work.

Install the Google Play Services SDK

Before you proceed to have location support in your Android Applications, you need to set-up Google Play Services SDK using following simple steps −
StepsDescription
1Launch Android Studio IDE
  • From Android Studio select file >project structure >dependencies > Click on + button to add dependencies
  • you would get choose library dependencies dialog window
2Search for com.google.android.gms:play-services:6.5.87 or higher version library. its depend on which android version is using with.
3Select the google play services and press apply button as shown below image

Create Android Application

StepDescription
1You will use Android studio IDE to create an Android application and name it asTutorialspoint under a package com.example.Tutorialspoint. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Add Google Play Service library in your project by following simple steps given below.
3Modify src/MainActivity.java file and add required code as shown below to take care of getting current location and its equivalent address.
4Modify layout XML file res/layout/activity_main.xml to add all GUI components which include three buttons and two text views to show location/address.
5Modify res/values/strings.xml to define required constant values
6Modify AndroidManifest.xml as shown below
7Run the application to launch Android emulator and verify the result of the changes done in the application.
Let's add Google Play Service reference in the project.Click on file > project structure > dependencies > and select + and then search google play services which will showcom.google.android.gms:play-services:6.5.87 Click on ok button. it will close the choose dependencies windows. you must be close project structure by clicking apply button
Google Play Service
Above image is showing the result of adding google play services to project. after add google play services to project. It should be as follows
Location
Following is the content of the modified main activity filesrc/com.example.Tutorialspoint/MainActivity.java.
package com.example.Tutorialspoint;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;

import android.content.Context;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import android.util.Log;
import android.view.View;

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

public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener
{
   LocationClient mLocationClient;
   private TextView addressLabel;
   private TextView locationLabel;
   private Button getLocationBtn;
   private Button disconnectBtn;
   private Button connectBtn;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      locationLabel = (TextView) findViewById(R.id.locationLabel);
      addressLabel = (TextView) findViewById(R.id.addressLabel);
      getLocationBtn = (Button) findViewById(R.id.getLocation);
      
      getLocationBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            displayCurrentLocation();
         }
      });
      
      disconnectBtn = (Button) findViewById(R.id.disconnect);
      disconnectBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            mLocationClient.disconnect();
            locationLabel.setText("Got disconnected....");
         }
      });
      
      connectBtn = (Button) findViewById(R.id.connect);
      connectBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            mLocationClient.connect();
            locationLabel.setText("Got connected....");
         }
      });
      
      // Create the LocationRequest object
      mLocationClient = new LocationClient(this, this, this);
   }
   
   @Override
   protected void onStart() {
      super.onStart();
      
      // Connect the client.
      mLocationClient.connect();
      locationLabel.setText("Got connected....");
   }
   
   @Override
   protected void onStop() {
      // Disconnect the client.
      mLocationClient.disconnect();
      super.onStop();
      locationLabel.setText("Got disconnected....");
   }
   
   @Override
   public void onConnected(Bundle dataBundle) {
      // Display the connection status
      Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
   }
   
   @Override
   public void onDisconnected() {
      // Display the connection status
      Toast.makeText(this, "Disconnected. Please re-connect.",Toast.LENGTH_SHORT).show();
   }
   
   @Override
   public void onConnectionFailed(ConnectionResult connectionResult) {
      // Display the error code on failure
      Toast.makeText(this, "Connection Failure : " + connectionResult.getErrorCode(),Toast.LENGTH_SHORT).show();
   }
   
   public void displayCurrentLocation() {
      // Get the current location's latitude & longitude
      Location currentLocation = mLocationClient.getLastLocation();
      String msg = "Current Location: " + 
      Double.toString(currentLocation.getLatitude()) + "," +
      Double.toString(currentLocation.getLongitude());
      
      // Display the current location in the UI
      locationLabel.setText(msg);
      
      // To display the current address in the UI
      (new GetAddressTask(this)).execute(currentLocation);
   }
   /*
   * Following is a subclass of AsyncTask which has been used to get
   * address corresponding to the given latitude & longitude.
   */
   private class GetAddressTask extends AsyncTask<Location, Void, String>{
      Context mContext;
      
      public GetAddressTask(Context context) {
         super();
         mContext = context;
      }
      /*
      * When the task finishes, onPostExecute() displays the address.
      */
      @Override
      protected void onPostExecute(String address) {
         // Display the current address in the UI
         addressLabel.setText(address);
      }
      
      @Override
      protected String doInBackground(Location... params) {
         Geocoder geocoder =new Geocoder(mContext, Locale.getDefault());
         
         // Get the current location from the input parameter list
         Location loc = params[0];
         
         // Create a list to contain the result address
         <Address> addresses = null;
         try {
            addresses = geocoder.getFromLocation(loc.getLatitude(),loc.getLongitude(), 1);
         }
         
         catch (IOException e1) {
            Log.e("LocationSampleActivity",IO Exception in getFromLocation());
            e1.printStackTrace();
            return ("IO Exception trying to get address");
         }
         
         catch (IllegalArgumentException e2) {
            // Error message to post in the log
            String errorString = "Illegal arguments " +
            Double.toString(loc.getLatitude()) +" , " +Double.toString(loc.getLongitude()) +" passed to address service";
            Log.e("LocationSampleActivity", errorString);
            e2.printStackTrace();
            return errorString;
         }
         // If the reverse geocode returned an address
         if (addresses != null && addresses.size() > 0) {
            // Get the first address
            Address address = addresses.get(0);
            
            /*
            * Format the first line of address (if available),
            * city, and country name.
            */
            String addressText = String.format("%s, %s, %s");
            
            // If there's a street address, add it
            address.getMaxAddressLineIndex() > 0 ?
            address.getAddressLine(0) : "",
            
            // Locality is usually a city
            address.getLocality(),
            
            // The country of the address
            address.getCountryName());
            
            // Return the text
            return addressText;
         }
         else {
            return "No address found";
         }
      }
   }// AsyncTask class
}
Following will be the content of res/layout/activity_main.xml file −
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >
   
   <TextView android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Location Example"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />

   <TextView android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_below="@+id/textView1"
      android:layout_alignRight="@+id/imageButton"
      android:layout_alignEnd="@+id/imageButton" />

   <ImageButton android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />

   <Button android:id="@+id/getLocation"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/get_location"/>
      
   <Button android:id="@+id/disconnect"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/disconnect"/>
      
   <Button android:id="@+id/connect"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/connect"/>
      
   <TextView
      android:id="@+id/locationLabel"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
      
   <TextView
      android:id="@+id/addressLabel"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
    
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new constants:
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">Tutorialspoint</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="get_location">Get Location</string>
   <string name="disconnect">Disconnect Service</string>
   <string name="connect">Connect Service</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.Tutorialspoint"
   android:versionCode="1"
   android:versionName="1.0" >
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
   
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.Tutorialspoint.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>
Let's try to run your Tutorialspoint application. I assume that, you have connected your actual Android Mobile device with your computer. To run the app from Android Studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application.
Android Mobile Device
Now to see location select Get Location Button which will display location information as follows −
Android Mobile Location Info
You can try by disconnecting location client using Disconnect Service and then connecting it by using Connect Service button. You can also modify to get location update as explained above and in Android Official documentation.
Email is messages distributed by electronic means from one system user to one or more recipients via a network
Before starting Email Activity, You must know Email functionality with intent, Intent is carrying data from one component to another component with-in the application or outside the application
To send an email from your application, you don’t have to implement an email client from the beginning, but you can use an existing one like the default Email app provided from Android, Gmail, Outlook, K-9 Mail etc. For this purpose, we need to write an Activity that launches an email client, using an implicit Intent with the right action and data. In this example, we are going to send an email from our app by using an Intent object that launches existing email clients.
Following section explains different parts of our Intent object required to send an email.

Intent Object - Action to send Email

You will use ACTION_SEND action to launch an email client installed on your Android device. Following is simple syntax to create an intent with ACTION_SEND action
Intent emailIntent = new Intent(Intent.ACTION_SEND);

Intent Object - Data/Type to send Email

To send an email you need to specify mailto: as URI using setData() method and data type will be to text/plain using setType() method as follows −
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");

Intent Object - Extra to send Email

Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be attached to the intent before sending the intent to a target email client. You can use following extra fields in your email −
Sr.No.Extra Data & Description
1EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.
2EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.
3EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.
4EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND to supply an alternative to EXTRA_TEXT as HTML formatted text.
5EXTRA_SUBJECT
A constant string holding the desired subject line of a message.
6EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with ACTION_SEND to supply the literal data to be sent.
7EXTRA_TITLE
A CharSequence dialog title to provide to the user when used with a ACTION_CHOOSER.
Here is an example showing you how to assign extra data to your intent −
emailIntent.putExtra(Intent.EXTRA_EMAIL  , new String[]{"Recipient"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(Intent.EXTRA_TEXT   , "Message Body");
The out-put of above code is as below shown an image
Email

EMAIL EXAMPLE

Example

Following example shows you in practical how to use Intent object to launch Email client to send an Email to the given recipients.
To Email experiment with this example, you will need actual Mobile device equipped with latest Android OS(Android lollipop), otherwise you might get struggle with emulator which may not work properly. Second you will need to have an Email client like GMail(By default every android version having Gmail client App) or K9mail installed on your device.
StepDescription
1You will use Android studio to create an Android application and name it asTutorialspoint under a package com.example.tutorialspoint. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file and add required code to take care of sending email.
3Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm adding a simple button to launch Email Client.
4Modify res/values/strings.xml to define required constant values
5Modify AndroidManifest.xml as shown below
6Run the application to launch Android emulator and verify the result of the changes done in the application.
Following is the content of the modified main activity filesrc/com.example.Tutorialspoint/MainActivity.java.
package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      Button startBtn = (Button) findViewById(R.id.sendEmail);
      startBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            sendEmail();
         }
      });
   }
   protected void sendEmail() {
      Log.i("Send email", "");
      String[] TO = {""};
      String[] CC = {""};
      Intent emailIntent = new Intent(Intent.ACTION_SEND);
      
      emailIntent.setData(Uri.parse("mailto:"));
      emailIntent.setType("text/plain");
      emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
      emailIntent.putExtra(Intent.EXTRA_CC, CC);
      emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
      emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");
      
      try {
         startActivity(Intent.createChooser(emailIntent, "Send mail..."));
         finish();
         Log.i("Finished sending email...", "");
      }
      catch (android.content.ActivityNotFoundException ex) {
         Toast.makeText(MainActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
      }
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}
Following will be the content of res/layout/activity_main.xml file −
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >
   
   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Sending Mail Example"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_above="@+id/imageButton"
      android:layout_alignRight="@+id/imageButton"
      android:layout_alignEnd="@+id/imageButton" />
      
   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true" />
      
   <Button 
      android:id="@+id/sendEmail"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/compose_email"/>
    
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">Tutorialspoint</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
   <string name="compose_email">Compose Email</string>
</resources>
Following is the default content of AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.Tutorialspoint"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.tutorialspoint.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>
Let's try to run your tutorialspoint application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android Studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application.Select your mobile device as an option and then check your mobile device which will display following screen −
Android Mobile Device
Now use Compose Email button to list down all the installed email clients. From the list, you can choose one of email clients to send your email. I'm going to use Gmail client to send my email which will have all the provided defaults fields available as shown below. Here From: will be default email ID you have registered for your Android device.
Android Mobile Gmail Screen
You can modify either of the given default fields and finally use send email button to send your email to the mentioned recipients.
In Android, you can use SmsManager API or devices Built-in SMS application to send SMS's. In this tutorial, we shows you two basic examples to send SMS message −
SmsManager API
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
Built-in SMS application
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content"); 
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
Of course, both need SEND_SMS permission.
<uses-permission android:name="android.permission.SEND_SMS" />
Apart from the above method, there are few other important functions available in SmsManager class. These methods are listed below −
Sr.No.Method & Description
1ArrayList<String> divideMessage(String text)
This method divides a message text into several fragments, none bigger than the maximum SMS message size.
2static SmsManager getDefault()
This method is used to get the default instance of the SmsManager
3void sendDataMessage(String destinationAddress, String scAddress, short destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent)
This method is used to send a data based SMS to a specific application port.
4void sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents)
Send a multi-part text based SMS.
5void sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)
Send a text based SMS.

Example

Following example shows you in practical how to use SmsManager object to send an SMS to the given mobile number.
To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work.
StepDescription
1You will use Android Studio IDE to create an Android application and name it astutorialspoint under a package com.example.tutorialspoint. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file and add required code to take care of sending email.
3Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm adding a simple GUI to take mobile number and SMS text to be sent and a simple button to send SMS.
4No need to define default string constants at res/values/strings.xml. Android studio takes care of default constants.
5Modify AndroidManifest.xml as shown below
6Run the application to launch Android emulator and verify the result of the changes done in the application.
Following is the content of the modified main activity filesrc/com.example.tutorialspoint/MainActivity.java.
package com.example.tutorialspoint;

import android.os.Bundle;
import android.app.Activity;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
   Button sendBtn;
   EditText txtphoneNo;
   EditText txtMessage;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      sendBtn = (Button) findViewById(R.id.btnSendSMS);
      txtphoneNo = (EditText) findViewById(R.id.editText);
      txtMessage = (EditText) findViewById(R.id.editText2);

      sendBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            sendSMSMessage();
         }
      });
   }
   protected void sendSMSMessage() {
      Log.i("Send SMS", "");
      String phoneNo = txtphoneNo.getText().toString();
      String message = txtMessage.getText().toString();
      
      try {
         SmsManager smsManager = SmsManager.getDefault();
         smsManager.sendTextMessage(phoneNo, null, message, null, null);
         Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
      } 
      
      catch (Exception e) {
         Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
         e.printStackTrace();
      }
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}
Following will be the content of res/layout/activity_main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context="MainActivity">

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Sending SMS Example"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_below="@+id/textView1"
      android:layout_alignRight="@+id/imageButton"
      android:layout_alignEnd="@+id/imageButton" />
      
   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:hint="Enter Phone Number"
      android:phoneNumber="true"
      android:textColorHint="@color/abc_primary_text_material_dark"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true" />

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText2"
      android:layout_below="@+id/editText"
      android:layout_alignLeft="@+id/editText"
      android:layout_alignStart="@+id/editText"
      android:textColorHint="@color/abc_primary_text_material_dark"
      android:layout_alignRight="@+id/imageButton"
      android:layout_alignEnd="@+id/imageButton"
      android:hint="Enter SMS" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Send Sms"
      android:id="@+id/btnSendSMS"
      android:layout_below="@+id/editText2"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="48dp" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">tutorialspoint</string>
   <string name="action_settings">Settings</string>
</resources>
Following is the default content of AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.tutorialspoint"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="22" />
   <uses-permission android:name="android.permission.SEND_SMS" />
   
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.tutorialspoint.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>
Let's try to run your tutorialspoint application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application.
Android Mobile Device
Now you can enter a desired mobile number and a text message to be sent on that number. Finally click on Send SMS button to send your SMS. Make sure your GSM/CDMA connection is working fine to deliver your SMS to its recipient.
You can take a number of SMS separated by comma and then inside your program you will have to parse them into an array string and finally you can use a loop to send message to all the given numbers. That's how you can write your own SMS client. Next section will show you how to use existing SMS client to send SMS.

Using Built-in Intent to send SMS

You can use Android Intent to send SMS by calling built-in SMS functionality of the Android. Following section explains different parts of our Intent object required to send an SMS.

Intent Object - Action to send SMS

You will use ACTION_VIEW action to launch an SMS client installed on your Android device. Following is simple syntax to create an intent with ACTION_VIEW action
Intent smsIntent = new Intent(Intent.ACTION_VIEW);

Intent Object - Data/Type to send SMS

To send an SMS you need to specify smsto: as URI using setData() method and data type will be to vnd.android-dir/mms-sms using setType() method as follows −
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");

Intent Object - Extra to send SMS

Android has built-in support to add phone number and text message to send an SMS as follows −
smsIntent.putExtra("address"  , new String("0123456789;3393993300"));
smsIntent.putExtra("sms_body"  , "Test SMS to Angilla");
Here address and sms_body are case sensitive and should be specified in small characters only. You can specify more than one number in single string but separated by semi-colon (;).

Example

Following example shows you in practical how to use Intent object to launch SMS client to send an SMS to the given recipients.
To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work.
StepDescription
1You will use Android studio IDE to create an Android application and name it astutorialspoint under a package com.example.tutorialspoint. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file and add required code to take care of sending SMS.
3Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm adding a simple button to launch SMS Client.
4No need to define default constants.Android studio takes care of default constants.
5Modify AndroidManifest.xml as shown below
6Run the application to launch Android emulator and verify the result of the changes done in the application.
Following is the content of the modified main activity filesrc/com.example.tutorialspoint/MainActivity.java.
package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      Button startBtn = (Button) findViewById(R.id.button);
      startBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            sendSMS();
         }
      });
   }
   
   protected void sendSMS() {
      Log.i("Send SMS", "");
      Intent smsIntent = new Intent(Intent.ACTION_VIEW);
      
      smsIntent.setData(Uri.parse("smsto:"));
      smsIntent.setType("vnd.android-dir/mms-sms");
      smsIntent.putExtra("address"  , new String ("01234"));
      smsIntent.putExtra("sms_body"  , "Test ");
      
      try {
         startActivity(smsIntent);
         finish();
         Log.i("Finished sending SMS...", "");
      }
      catch (android.content.ActivityNotFoundException ex) {
         Toast.makeText(MainActivity.this, 
         "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
      }
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" 
   tools:context=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Drag and Drop Example"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point "
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="30dp"
      android:textColor="#ff14be3c" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_marginTop="48dp"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Compose SMS"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_marginTop="54dp"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />
      
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">tutorialspoint</string>
   <string name="action_settings">Settings</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.tutorialspoint"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="22" />
      
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.tutorialspoint.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>
Let's try to run your tutorialspoint application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application.
Android Mobile Device
Select your mobile device as an option and then check your mobile device which will display following screen:
Android Mobile SMS Compose
Now use Compose SMS button to launch Android built-in SMS clients which is shown below:
Android Mobile SMS Screen
You can modify either of the given default fields and finally use send SMS button to send your SMS to the mentioned recipient.
Android provides Built-in applications for phone calls, in some occasions we may need to make a phone call through our application. This could easily be done by using implicit Intent with appropriate actions. Also, we can use PhoneStateListener and TelephonyManager classes, in order to monitor the changes in some telephony states on the device.
This chapter lists down all the simple steps to create an application which can be used to make a Phone Call. You can use Android Intent to make phone call by calling built-in Phone Call functionality of the Android. Following section explains different parts of our Intent object required to make a call.

Intent Object - Action to make Phone Call

You will use ACTION_CALL action to trigger built-in phone call functionality available in Android device. Following is simple syntax to create an intent with ACTION_CALL action
Intent phoneIntent = new Intent(Intent.ACTION_CALL);
You can use ACTION_DIAL action instead of ACTION_CALL, in that case you will have option to modify hardcoded phone number before making a call instead of making a direct call.

Intent Object - Data/Type to make Phone Call

To make a phone call at a given number 91-000-000-0000, you need to specify tel: as URI using setData() method as follows −
phoneIntent.setData(Uri.parse("tel:91-000-000-0000"));
The interesting point is that, to make a phone call, you do not need to specify any extra data or data type.

Example

Following example shows you in practical how to use Android Intent to make phone call to the given mobile number.
To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work.
StepDescription
1You will use Android studio IDE to create an Android application and name it asMy Application under a package com.example.saira_000.myapplication. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file and add required code to take care of making a call.
3Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm adding a simple button to Call 91-000-000-0000 number
4No need to define default string constants.Android studio takes care of default constants.
5Modify AndroidManifest.xml as shown below
6Run the application to launch Android emulator and verify the result of the changes done in the application.
Following is the content of the modified main activity file src/MainActivity.java.
package com.example.saira_000.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {
   Button b1;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      b1=(Button)findViewById(R.id.button);
      call();
   }
   
   private void call() {
      Intent in=new Intent(Intent.ACTION_CALL,Uri.parse("0000000000"));
      try{
         startActivity(in);
      }
      
      catch (android.content.ActivityNotFoundException ex){
         Toast.makeText(getApplicationContext(),"yourActivity is not founded",Toast.LENGTH_SHORT).show();
      }
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" 
   tools:context=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Drag and Drop Example"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="30dp"
      android:textColor="#ff14be3c" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_marginTop="48dp"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Call"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_marginTop="54dp"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">My Application</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.saira_000.myapplication"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-permission android:name="android.permission.CALL_PHONE" />
   <uses-permission android:name="android.permission.READ_PHONE_STATE" />
   
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.saira_000.myapplication.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>
Let's try to run your My Application application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application.
Android Mobile Device
Select your mobile device as an option and then check your mobile device which will display following screen −
Android Mobile Call Screen
Now use Call button to make phone call as shown below:
Android Mobile Call Progress
Android application publishing is a process that makes your Android applications available to users. Infect, publishing is the last phase of the Android application development process.
Publish

ANDROID DEVELOPMENT LIFE CYCLE

Once you developed and fully tested your Android Application, you can start selling or distributing free using Google Play (A famous Android marketplace). You can also release your applications by sending them directly to users or by letting users download them from your own website.
You can check a detailed publishing process at Android official website, but this tutorial will take you through simple steps to launch your application on Google Play. Here is a simplified check list which will help you in launching your Android application −
StepActivity
1Regression Testing Before you publish your application, you need to make sure that its meeting the basic quality expectations for all Android apps, on all of the devices that you are targeting. So perform all the required testing on different devices including phone and tablets.
2Application Rating When you will publish your application at Google Play, you will have to specify a content rating for your app, which informs Google Play users of its maturity level. Currently available ratings are (a) Everyone (b) Low maturity (c) Medium maturity (d) High maturity.
3Targeted Regions Google Play lets you control what countries and territories where your application will be sold. Accordingly you must take care of setting up time zone, localization or any other specific requirement as per the targeted region.
4Application Size Currently, the maximum size for an APK published on Google Play is 50 MB. If your app exceeds that size, or if you want to offer a secondary download, you can use APK Expansion Files, which Google Play will host for free on its server infrastructure and automatically handle the download to devices.
5SDK and Screen Compatibility It is important to make sure that your app is designed to run properly on the Android platform versions and device screen sizes that you want to target.
6Application Pricing Deciding whether you app will be free or paid is important because, on Google Play, free app's must remain free. If you want to sell your application then you will have to specify its price in different currencies.
7Promotional Content It is a good marketing practice to supply a variety of high-quality graphic assets to showcase your app or brand. After you publish, these appear on your product details page, in store listings and search results, and elsewhere.
8Build and Upload release-ready APK The release-ready APK is what you you will upload to the Developer Console and distribute to users. You can check complete detail on how to create a release-ready version of your app: Preparing for Release.
9Finalize Application Detail Google Play gives you a variety of ways to promote your app and engage with users on your product details page, from colourful graphics, screen shots, and videos to localized descriptions, release details, and links to your other apps. So you can decorate your application page and provide as much as clear crisp detail you can provide.

Export Android Application Process

Android Application Process

APK DEVELOPMENT PROCESS

Before exporting the apps, you must some of tools
  • Dx tools(Dalvik executable tools ): It going to convert .class file to .dex file. it has useful for memory optimization and reduce the boot-up speed time
  • AAPT(Android assistance packaging tool):it has useful to convert .Dex file to.Apk
  • APK(Android packaging kit): The final stage of deployment process is called as .apk.
You will need to export your application as an APK (Android Package) file before you upload it Google Play marketplace.
To export an application, just open that application project in Android studio and selectBuild → Generate Signed APK from your Android studio and follow the simple steps to export your application −
Generate Signed APK
Next select, Generate Signed APK option as shown in the above screen shot and then click it so that you get following screen where you will choose Create new keystore to store your application.
Generate Signed APK
Enter your key store path,key store password,key alias and key password to protect your application and click on Next button once again. It will display following screen to let you create an application:
Generate Signed APK
Once you filled up all the information,like app destination,build type and flavours clickfinish button While creating an application it will show as below
Creating Application
Finally, it will generate your Android Application as APK formate File which will be uploaded at Google Play marketplace.

Google Play Registration

The most important step is to register with Google Play using Google Play Marketplace. You can use your existing google ID if you have any otherwise you can create a new Google ID and then register with the marketplace. You will have following screen to accept terms and condition.
Android Market Place Terms and Conditions
You can use Continue to payment button to proceed to make a payment of $25 as a registration fee and finally to complete your account detail.
Once you are a registered user at Google Play, you can upload release-ready APK for your application and finally you will complete application detail using application detail page as mentioned in step 9 of the above mentioned checklist.

Signing Your App Manually

You do not need Android Studio to sign your app. You can sign your app from the command line using standard tools from the Android SDK and the JDK. To sign an app in release mode from the command line −
  • Generate a private key using keytool
$ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000
  • Compile your app in release mode to obtain an unsigned APK
  • Sign your app with your private key using jarsigner −
$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1
-keystore my-release-key.keystore my_application.apk alias_name
  • Verify that your APK is signed. For example −
$ jarsigner -verify -verbose -certs my_application.apk
  • Align the final APK package using zipalign.
$ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk

No comments:

Easy Way to Handle Android Notifications

Android Notifications Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persist...