Tuesday 25 August 2015

ANDROID_BASIC

What is Android ?

Android has come a long since its inception in 2005 - A lot of things have changed from Cupcake to Marshmallow.  We have not only seen great Android Phones but a mature operation system and beautiful App experience.
Though a lot has changed since the launch of Android, the basic building blocks of Android app have remained the same. Let's look at some of the basic building blocks of an Android app in detail. Later, we will see how all these components come together to create an app, using the example of a Twitter application.
An Android Application is coded in Java and compiled into a single distribution package called as APK. APK is the executable file which is installed on your phone as Android app. Let's walk through the various building blocks of the an Android application.

The basic building blocks of any Android app are - Activities, Views and Intents. These are a must in any Android app
Services, Content Provider and Broadcast are some of the advance features which add more functionality to your app
Let's go 1 by 1 into each of these components and get more details about them.

Activity

This is the first Android component you will encounter as soon as you open an Android app. An Android app should have at least one Activity in it.
·         So what exactly is Activity ? Every screen in an Android app is an Activity. Activity will always have a User Interface (abbreviated as UI). It is not possible to have an Activity without a UI.
·         Any Android app has one or more Activities. Out of these, one Activity will act as the entry point. The Activity will show up when the app starts. This is usually referred to as the launcher Activity or the main Activity too.
·         Every Activity has its own lifecycle. You can read more about it in the Activity Concept Lesson .
·         Every Android app has a Manifest.xml where all Activites are defined and one Activity is marked as Main Activity. One of the most common error developers commit when they start with Android development is forgetting to add a new Activity in Mainfest.xml file.
As a developer, Activity is a Java class file where you write the logic. Activity does not include the UI. Rather, one of the things you need to write in your Activity logic is - which UI to show. 

User Interface / Views

User Interface or UI is what the user sees on the screen. The Activity has the responsibility to set the UI for the screen. UI comprises primarily of two type of sub-components. Views & Layouts or ViewGroups.
View as the name suggest is the basic building block like buttons, label, input-box etc. Layout is the container for View elements. The Layout primarily defines the pattern in which the View element should show up. Eg. LinearLayout mandates that the View elements inside it either stack up horizontally or vertically while RelativeLayout lets each View element position itself relative to the parent or a sibling element.
UI is defined as XML. The top XML element is a Layout element . Inside it, there can be either View elements or Layout elements. An example XML file is shown below.
 <LinearLayout 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:orientation="horizontal" >
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 3" />
 </LinearLayout>
You may read more about Layouts & Views in our Layout Concept Lesson & View Concept Lesson.

Intents

To move from one Activity to another (or one screen to another), on user interaction like click of a button or click of a notification item, Intents are used. It is possible to pass data including whole objects with Intent. Using Intent you can also open another Android application.
Apart from launching an Activity, Intent can also launch a Service.
With Activity, Views and Intent; you can create a basic Android app. Lots of apps are made by using only these three concepts.
Let’s look into some of the advanced Android concepts.
Services
Have you ever listened to Music on your phone? Have you observed that the music continues to play in the background when you go to the home screen from the Music app or close the app?
This is achieved using Services. Services is the Android way of keeping an operation going on in the background. When you need to have long running tasks like playing music, downloading data or uploading photos; it is achieved through Service.
Service doesn’t have any UI. To show any information to the user from Service, Notifications are used.
There are two ways in which you can create a Service. One way is to tie the Service with an Activity. In this case, the Service will end once Activity stops. The other way is to run a Service independent of any Application. This way, the Service keeps running in the background even after the application is stopped.
SQLite (Database) in Android
Android ships with SQLite database support. Android apps can store data locally in the SQLite database. Every Android application can create its own private SQLite databases which it can use to store data for offline reference.
The purpose of storing data locally is primarily to provide a good user experience. Consider the example of the Android Twitter app. When you open the app, you immediately see the tweet list while there is a loading symbol shown which conveys that the tweets are still being fetched. The tweet list is stale, but you do not have to wait for the tweets to load because the app has stored the tweets locally.
There are other options apart from the database to store data in an Android app. Information of small sizes can be stored in Shared Preferences. You can also create local files & store data in it.
Content Providers
If your Android app wants to use data from another Android app, you may use Content Providers.
A simple example of Content Provider is the Contacts app. You can get contacts in multiple applications like your SMS application, Dialer Application etc.
If you are using SQLite/database in your app, you can either access it directly or through a Content Provider. Content Provider gives you encapsulated access.
Notifications
Earlier in the Services section, we came across Notifications. If you have used an Android phone, you would have seen small notifications in the top part of your phone for missed call, SMS or email received etc. These are Notifications.
·         Notifications are simple messages which are used to display information to user that doesn’t require user’s immediate attention
·         Typically notification comes with Text and Small icon, but newer version of Android support richer notification with buttons and images
·         User can tap on notification and can interact with it
Notifications are the most widely used functionality in Android, from SMS to missed call, from wifi network connection to Twitter notifications. They are used everywhere.
Broadcast Receivers
Broadcast receiver is a way to listen to systemwide events happening in your phone or tablet. Using Broadcast Receivers, we can create some great applications like Call Number finder, SMS blocker etc, which works when some events happen in your device.
Many systemwide events broadcast their information. For example
·         When SMS / Call is received
·         Battery low
·         Network state Changed
·         Photo captured from camera
·         Phone Starts
We can also generate custom broadcast from inside our application. Whenever you want to create any application which works with system events use broadcast receiver
Broadcast receivers work even if your application is not running. That means you can create functionality in your application which can be invoked automatically by Android if something happens without actually running any service or application in the background.
So we have seen how different components are available to create any application in Android, now let's look into an application like twitter and see all these components in action.

Services, BroadCast Receiver & Database

Pulling down the ListView screen invokes a Service which runs in background to update the activity with new tweets.
While this Service is activated, the Activity keeps showing a 'Loading' sign. The tweets are locally stored in the Twitter app. The Service is supposed to update the tweets in the SQLite database. A Broadcast Receiver is setup to listen to the event which is triggered when the Service ends. The Broadcast Receiver updates the tweet list & hides the 'Loading' sign too.

Content Provider for database access

The tweets once loaded are accessible even when there is no network connection. As mentioned earlier, the tweets are stored in the database. Otherwise, it would not be possible to show the tweets when the app is offline.
Typically you never access a database directly. Instead Twitter app may be using Content Provider. Content Provider helps to provide abstraction over how data is stored and accessed in an application.

Notifications

If you come out of the Twitter app, a Service is started in the background. This service occasionally checks for new tweets and displays a notification if there is an update.
Service is one way but to prevent app from draining battery, the Twitter app might be using Push Notification. Push notification are a way to push data to application even if application is not running.


Android Activity Life Cycle

Android Activity
Android Activity is the basic building block of an Android App. Android Activity always has a User Interface. Android apps consist of one or many Activities. We also saw that to tell Android, which activity to open when the application is launched, we defined Main Activity in Manifest.xml.
An Android Activity has a Lifecycle during which it performs a few things. The first question when reading about Lifecycle of Activity Lifecycle is - Why is it required ? Let's understand it with an example.
Assume you are playing a game on your phone, you are at level 2 and suddenly some one calls you. When you get a call, your games stop and you see the Caller Id Screen. When you resume your game after the call ends, it gets resumed from the same point where you left it.
Now assume you are a game developer. For you, there should be a way to save the game state. Right? How will this happen? To make developer's life easier, Android has something called Activity Lifecycle. Consider Lifecycle to be a collection of callback functions getting called whenever something happens to your application (or Activity to be more precise).

Activity Lifecycle


The above image shows various functions like 'onCreate()', 'onStart()' which gets called at various points of an Activity Lifecycle. Let's look at each of the methods/functions in detail.
onCreate
onCreate() is called when your Activity is getting created for the first time. It is called only once during the entire Activity Lifecycle. One of the important things you are supposed to do is to set the Activity Layout through setContentView function.
Also, you can use onCreate to initialize your variables. In any Android application, whenever you create an Activity, the minimum method which you need to override is onCreate.
class MainActivity extends Activity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
end
If you notice, OnCreate function is getting passed a variable of class Bundle. Bundle is typically used to store the state of your Activity. Take the example of screen rotation, during which your Activity gets killed and OnCreate is called again. You can determine if the Activity was already there using Bundle so that you do not have to create the Activity again.
Why is this necessary, imagine you have a form and user has already filled some of the fields. Suddenly the user rotates his screen. Using Bundle, Android retains the values of these fields and re-populates the data after rotation automatically. The value of Bundle will always be null when Activity is getting created for the first time.
onStart:
onStart gets called just before the Activity becomes visible to the user. If you notice, onStart is called from two places - after onRestart and OnCreate. onStart is always followed by OnResume or OnStop. You can use onStart to reset Activity data, reinitialize variables etc.
onResume:
onResume gets called when your Activity comes into the foreground, and it becomes visible to the user. At this point, the Activity is on top of the Activity stack, and the user can start interacting with the Activity. onResume is typically used to register Listeners, bind to Services etc.
onResume is a good place to refresh your UI with any new changes which might have occurred during the period in which the Activity was not visible. For example, if you are polling a Service in the background (like checking for new tweets), onResume is a good place to update your screen with new results.
onPause:
onPause is called when another android activity comes on top of your Activity. Typically anything that steals your user away from your Activity will result in onPause.
In OnPause, we either release the resources, or save the application data, or stop background threads etc.
It is always guaranteed that whenever your Activity is becoming invisible or partially invisible, onPause will be called. But once onPause is called, Android reserves the right to kill your Activity at any point. Hence you should not be relying on receiving any further events.
onStop:
onStop is called when your Activity is no longer visible to the user, it is similar to onPause but here you will not see your android activity entirely. You can use this method as well to store the state of your application and shut down time intensive or CPU intensive operations. This method is guaranteed to be called as of API level 11.
So what is the difference between onPause and OnStop ? If an Activity comes into the foreground and fills the screen such that your current activity is not at all visible, your current android activity will be called with both onPause and onStop . If, however, an Activity that comes to foreground does not fill the screen and your current Activity is partially visible, your current Activity will be called with only onPause.
Typically whenever you see a dialog box which requires your attention like battery low, network connection your current android activity becomes partially visible and popup box comes on the top. This is the point where only onPause will be called.
onRestart:
It is similar to onCreate, but onRestart gets called only after onStop. This is the method which you can use to know if your application is starting afresh or getting restarted.
In onRestart, you will get your application to save the state and reinitialize all the variables. onStart gets called after this.
OnDestroy:
This is the method which will be called when your Activity is getting killed. This is the final call the Activity will receive in its Lifecycle.
When the user press back button on any Activity the foreground activity gets destroyed and control will return to the previous Activity.
But remember the fact, there is no guaranty that onDestroy will be called. Only when the system is low on resources or user press the back button or if you use finish() explicitly in your code, onDestroy gets called.
Even though you should always use onPause and onStop to clean up resources, release connections etc; onDestory is there to let your app have the final chance to clean things up before the Activity cease to exist.
So we have seen the complete Activity Lifecycle functions. Lets see what are the different states of an Activity.
Activity States
The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state in which an Android Activity is, it will be assigned a priority within the OS. This system helps Android identify Activities that are no longer in use, allowing Android to reclaim memory and resources. Following are the states an Activity can go through during its lifetime:
Active or Running
Activities are considered active or running if they are in the foreground. This state denotes the top of the Activity stack. The Activity gets assigned the highest priority and will only be killed by Android in extreme situations, such as if the Activity tries to use more memory more than what is available on the device. It can cause the Activity to become unresponsive.
Paused
An Android Activity is in the Paused state if the device goes to sleep or if it is covered with another Activity partially or completely. Paused activities are very much alive, that is, they maintain all the states and member information. They remain attached to the window manager too. This is considered to be the second highest priority in the Android Activity stack. Paused Activites will only get killed by Android to keep the Active/Running Activity stable and responsive.
Stopped
Android Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states.
Android Activity Lifecycle Example App
We have seen various states of Android Activity and seen all the Lifecycle methods. Let's walk through a code example and see these Lifecycle methods in action.
First Run
When your application runs for the first time, you will see onCreate, OnStart and onResume method gets called. Notice the messages which gets displayed.
Stopping
Press the home button and exit the app. You will notice that when you press the home button, onPause is called first followed by onStop
Restarting
Now open the application again by clicking on the application icon. Notice that you will see onRestart getting called followed by OnStart and OnResume
Destroy
Now once you saw onRestart, just press the back button, this will exit your application but notice that onDestory is called when you exit. And before onDestory, onPause and onStop is called.
Summarizing the chapter, you understood why an Activity Lifecycle exists, what is its importance and what are the different Lifecycle states which an activity goes through.


Different Types of Notifications in Android

You may have heard about Android Jelly Bean (API level 16). Google has improved a lot of features and introduced new features. One of them is the notification. Now they have made the notification more versatile by introducing media rich notification. Google has come up with three special style of notification which are mentioned below. Even developer can write his own customized notification style using remote view.The old Notification class constructor has been deprecated and a brand new and enhanced version of Notification has been introduced.

Notification Type:

  • Basic Notification – Shows simple and short notification with icon.
  • Big Picture Notification – Shows visual content such as bitmap.
  • Big Text Notification – Shows multiline Textview object.
  • Inbox Style Notification – Shows any kind of list, e.g messages, headline etc. 
Old syntax requires us to create an object of notification but now Android uses builder patter to create the notification object. Notification.Builder class has been introduced to make this task easier. This class returns the builder object which is configurable according to your requirements. The helper classes have been introduced like Notification.BigPictureStyle, Notification.BigTextStyle, and Notification.InboxStyle. These classes are re-builder classes which take object created by Notification.Builder class and  modify the behavior like so.

Activity_Notification.XML

<LinearLayout 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:orientation="vertical"
    android:gravity="center_horizontal">

    <Button
        android:id="@+id/btBasicNotification"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal|center_vertical"
        android:onClick="sendBasicNotification"
        android:text="BasicNotification" 
        
        android:textColor="#000000"
        />
    <Button
        android:id="@+id/btBigTextNotification"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal|center_vertical"
        android:onClick="sendBigTextStyleNotification"
        android:text="BigTextNotification" 
        
        android:textColor="#000000"
        />
   <Button
        android:id="@+id/btBigPictureNotification"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal|center_vertical"
        android:onClick="sendBigPictureStyleNotification"
        android:text="BigPictureNotification"
        
        android:textColor="#000000" />
   <Button
        android:id="@+id/btInboxStyleNotification"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal|center_vertical"
        android:onClick="sendInboxStyleNotification"
        android:text="InboxStyleNotification"
        
        android:textColor="#000000"/>
</LinearLayout>


NotificationActivity.Java

package com.example.notifications;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;


@SuppressLint("NewApi")
public class NotificationActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public void sendBasicNotification(View view) {
 Notification notification = new Notification.Builder(this)
   .setContentTitle("Basic Notification")
   .setContentText("Basic Notification, used earlier")
   .setSmallIcon(R.drawable.ic_launcher).build();
 notification.flags |= Notification.FLAG_AUTO_CANCEL;
 NotificationManager notificationManager = getNotificationManager();
 notificationManager.notify(0, notification);
}

public void sendBigTextStyleNotification(View view) {
 String msgText = "Jeally Bean Notification example!! "
   + "where you find three different kind of notification. "
   + "will see here different types of notifications";

 NotificationManager notificationManager = getNotificationManager();
 PendingIntent pi = getPendingIntent();
 android.app.Notification.Builder builder = new Notification.Builder(this);
 builder.setContentTitle("Big text Notofication")
   .setContentText("Big text Notification")
   .setSmallIcon(R.drawable.ic_launcher)
   //.setAutoCancel(true);
   .setPriority(Notification.PRIORITY_HIGH)
   .addAction(R.drawable.ic_launcher, "show activity", pi);
 Notification notification = new Notification.BigTextStyle(builder)
   .bigText(msgText).build();
 
 notificationManager.notify(0, notification);
}

public void sendBigPictureStyleNotification(View view) {
 PendingIntent pi = getPendingIntent();
 android.app.Notification.Builder builder = new Notification.Builder(this);
 builder.setContentTitle("BP notification")
   // Notification title
   .setContentText("BigPicutre notification")
   // you can put subject line.
   .setSmallIcon(R.drawable.ic_launcher)
   // Set your notification icon here.
   .addAction(R.drawable.ic_launcher, "show activity", pi)
   .addAction(
     R.drawable.ic_launcher,
     "Share",
     PendingIntent.getActivity(getApplicationContext(), 0,
       getIntent(), 0, null));

 // Now create the Big picture notification.
 Notification notification = new Notification.BigPictureStyle(builder)
   .bigPicture(
     BitmapFactory.decodeResource(getResources(),
       R.drawable.ic_launcher)).build();
 // Put the auto cancel notification flag
 notification.flags |= Notification.FLAG_AUTO_CANCEL;
 NotificationManager notificationManager = getNotificationManager();
 notificationManager.notify(0, notification);
}

public void sendInboxStyleNotification(View view) {
 PendingIntent pi = getPendingIntent();
 android.app.Notification.Builder builder = new Notification.Builder(this)
   .setContentTitle("IS Notification")
   .setContentText("Inbox Style notification!!")
   .setSmallIcon(R.drawable.ic_launcher)
   .addAction(R.drawable.ic_launcher, "show activity", pi);

 Notification notification = new Notification.InboxStyle(builder)
   .addLine("First message").addLine("Second message")
   .addLine("Thrid message").addLine("Fourth Message")
   .setSummaryText("+2 more").build();
 // Put the auto cancel notification flag
 notification.flags |= Notification.FLAG_AUTO_CANCEL;
 NotificationManager notificationManager = getNotificationManager();
 notificationManager.notify(0, notification);
}

public PendingIntent getPendingIntent() {
 return PendingIntent.getActivity(this, 0, new Intent(this,
   HandleNotificationActivity.class), 0);
}

public NotificationManager getNotificationManager() {
 return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
}
raj.XML

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


HandleNotificationActivity.Java

package com.example.notifications;
import android.app.Activity;
public class HandleNotificationActivity extends Activity{
import android.os.Bundle; @Override
// TODO Auto-generated method stub
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
}
setContentView(R.layout.raj); }









Ads Inside Post