Saturday, 23 April 2016

StartActivityForResult




By Android startActivityForResult() method, we can get result from another activity.

By the help of android startActivityForResult() method, we can send information from one activity to another and vice-versa. The android startActivityForResult method, requires a result from the second activity (activity to be invoked).

In such case, we need to override the onActivityResult method that is invoked automatically when second activity returns result.

Method Signature


There are two variants of startActivityForResult() method.



 public void startActivityForResult (Intent intent, int requestCode)   
 public void startActivityForResult (Intent intent, int requestCode, Bundle options)   



Example:




An Image capture from existing Camera Apps

A quick way to enable taking pictures or videos in your application without a lot of extra code is to use an Intent to invoke an existing Android camera application. A camera intent makes a request to capture a picture or video clip through an existing camera app and then returns control back to your application. This section shows you how to capture an image or video using this technique.

The procedure for invoking a camera intent follows these general steps:

Compose a Camera Intent - Create an Intent that requests an image or video, using one of these intent types:

MediaStore.ACTION_IMAGE_CAPTURE - Intent action type for requesting an image from an existing camera application.

Start the Camera Intent - Use the startActivityForResult() method to execute the camera intent. After you start the intent, the Camera application user interface appears on the device screen and the user can take a picture or video.



Receive the Intent Result - Set up an onActivityResult() method in your application to receive the callback and data from the camera intent. When the user finishes taking a picture or video (or cancels the operation), the system calls this method.



 private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;  
 private Uri fileUri;  
   
 @Override  
 public void onCreate(Bundle savedInstanceState) {  
   super.onCreate(savedInstanceState);  
   setContentView(R.layout.main);  
   
   // create Intent to take a picture and return control to the calling application  
   Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
   
   fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image  
   intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name  
   
   // start the image capture Intent  
   startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);  
 }  


When the startActivityForResult() method is executed, users see a camera application interface. After the user finishes taking a picture (or cancels the operation), the user interface returns to your application, and you must intercept the onActivityResult() method to receive the result of the intent and continue your application execution

Receiving camera intent result


Once you have constructed and executed an image or video camera intent, your application must be configured to receive the result of the intent. This section shows you how to intercept the callback from a camera intent so your application can do further processing of the captured image.



In order to receive the result of an intent, you must override the onActivityResult() in the activity that started the intent. The following example demonstrates how to override onActivityResult() to capture the result of the image camera intent camera intent examples shown in the previous sections.




 private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;  
   
 @Override  
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
   if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {  
     if (resultCode == RESULT_OK) {  
       // Image captured and saved to fileUri specified in the Intent  
       Toast.makeText(this, "Image saved to:\n" +  
            data.getData(), Toast.LENGTH_LONG).show();  
     } else if (resultCode == RESULT_CANCELED) {  
       // User cancelled the image capture  
     } else {  
       // Image capture failed, advise user  
     }  
   }  
   
 }  

Note: Any existing app which have hardware uses you need to add hardware uses and permission must. 

Manifest Declarations

Before starting development on your application with the Camera API, you should make sure your manifest has the appropriate declarations to allow use of camera hardware and other related features.

Camera Permission - Your application must request permission to use a device camera.


 <uses-permission android:name="android.permission.CAMERA" />  

Camera Features - Your application must also declare use of camera features, for example:


 <uses-feature android:name="android.hardware.camera" />  





Intent



Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services etc.

It is generally used with startActivity() method to invoke activity, broadcast receivers etc.


The dictionary meaning of intent is intention or purpose. So, it can be described as the intention to do action.


The LabeledIntent is the subclass of android.content.Intent class.


Android intents are mainly used to:





  • Start the service
  • Launch an activity
  • Display a web page
  • Display a list of contacts
  • Broadcast a message
  • Dial a phone call etc.


Types of Android Intents

There are two types of intents in android: implicit and explicit.

Implicit Intent

Implicit Intent doesn't specify the component. In such case, intent provides information of available components provided by the system that is to be invoked.

For example, you may write the following code to view the webpage.


 Intent intent=new Intent(Intent.ACTION_VIEW);   
 intent.setData(Uri.parse("http://androidtutorialforum.blogspot.in/"));   
 startActivity(intent);   

Explicit Intent

Explicit Intent specifies the component. In such case, intent provides the external class to be invoked it is call directly with class name.


 Intent intent = new Intent(getApplicationContext(), ExampleActivity.class);   
 startActivity(intent);   






Friday, 22 April 2016

Activity




An activity represents a single screen with a user interface. An application can have one or more activity. For example a contact app shows contact list might be an activity and where we create new contact it might be also other activity.


Activity Lifecycle

Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.



 Method        Description  
 onCreate      called when activity is first created.  
 onStart       called when activity is becoming visible to the user.  
 onResume      called when activity will start interacting with the user.  
 onPause       called when activity is not visible to the user.  
 onStop        called when activity is no longer visible to the user.  
 onRestart     called after your activity is stopped, prior to start.  
 onDestroy     called before the activity is destroyed.  




Android Activity Lifecycle Example




It provides the details about the invocation of life cycle methods of activity. In this example, we are displaying the content on the logcat.



 package com.androidtutorialforum.activitylifecycle;   
 import android.os.Bundle;   
 import android.app.Activity;   
 import android.util.Log;   
 import android.view.Menu;   
 public class MainActivity extends Activity {   
   @Override   
   protected void onCreate(Bundle savedInstanceState) {   
     super.onCreate(savedInstanceState);   
     setContentView(R.layout.activity_main);   
     Log.d("lifecycle","onCreate invoked");   
   }   
   @Override   
   protected void onStart() {   
     super.onStart();   
      Log.d("lifecycle","onStart invoked");   
   }   
   @Override   
   protected void onResume() {   
     super.onResume();   
      Log.d("lifecycle","onResume invoked");   
   }   
   @Override   
   protected void onPause() {   
     super.onPause();   
      Log.d("lifecycle","onPause invoked");   
   }   
   @Override   
   protected void onStop() {   
     super.onStop();   
      Log.d("lifecycle","onStop invoked");   
   }   
     @Override   
   protected void onRestart() {   
     super.onRestart();   
      Log.d("lifecycle","onRestart invoked");   
   }     
   @Override   
   protected void onDestroy() {   
     super.onDestroy();   
      Log.d("lifecycle","onDestroy invoked");   
   }   
 }   

Declaring the activity in the manifest


 <activity android:name=".MainActivity" android:icon="@drawable/app_icon">  
   <intent-filter>  
     <action android:name="android.intent.action.MAIN" />  
     <category android:name="android.intent.category.LAUNCHER" />  
   </intent-filter>  
 </activity>  




Input Controls





Input controls are the interactive components in your app's user interface. Android provides a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, checkboxes, zoom buttons, toggle buttons, and many more.

Adding an input control to your UI is as simple as adding an XML element to your XML layout.

Source:
http://developer.android.com/guide/topics/ui/controls.html









CheckBox


Android CheckBox is a type of two state button either checked or unchecked.

There can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the user, activate/deactivate the specific action etc.

Android CheckBox class is the subclass of CompoundButton class.

Android CheckBox class

The android.widget.CheckBox class provides the facility of creating the CheckBoxes.





ToggleButton



Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button.

It is beneficial if user have to change the setting between two states. It can be used to On/Off Sound, Wifi, Bluetooth etc.

Since Android 4.0, there is another type of toggle button called switch that provides slider control.

Android ToggleButton and Switch both are the subclasses of CompoundButton class.

Android ToggleButton class

ToggleButton class provides the facility of creating the toggle button.



Android ToggleButton class


ToggleButton class provides the facility of creating the toggle button.









Android Toast



Android Toast can be used to display information for the short period of time. A toast contains message to be displayed quickly and disappears after sometime.

The android.widget.Toast class is the subclass of java.lang.Object class.

You can also create custom toast as well for example toast displaying image. You can visit next page to see the code for custom toast.


Toast class




Toast class is used to show notification for a particular interval of time. After sometime it disappears. It doesn't block the user interaction.


Constants of Toast class


There are only 2 constants of Toast class which are given below.


Constant Description


 public static final int LENGTH_LONG      displays view for the long duration of time.  
 public static final int LENGTH_SHORT     displays view for the short duration of time.    


Toast Example

 Toast.makeText(getApplicationContext(),"Hello Android",Toast.LENGTH_SHORT).show();   

Custom Toast

 Toast toast=Toast.makeText(getApplicationContext(),"Hello Android",Toast.LENGTH_SHORT);   
 toast.setMargin(50,50);   
 toast.show();   







Monday, 18 April 2016

Button






Android Button represents a push-button. The android.widget.Button is subclass of TextView class and CompoundButton is the subclass of Button class.

There are different types of buttons in android such as RadioButton, ToggleButton, CompoundButton etc.








activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <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="com.androidtutorialforum.button.MainActivity">  
   
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Android Tutorial Forum" />  
   
   <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_centerHorizontal="true"  
     android:layout_centerVertical="true"  
     android:text="@string/button" />  
 </RelativeLayout>  
   






MainActivity.java

 package com.androidtutorialforum.button;  
   
 import android.support.v7.app.AppCompatActivity;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.widget.Button;  
   
   
 public class MainActivity extends AppCompatActivity {  
   
   private Button button;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     button=(Button)findViewById(R.id.button1);  
     button.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         // code here  
       }  
     });  
       
   }  
 }  
   




Sunday, 17 April 2016

Android Widgets



There are given a lot of android widgets with simplified examples such as Button, EditText, AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar etc.

Android widgets are easy to learn. The widely used android widgets with examples are given below:


Android Button

Let's learn how to perform event handling on button click.


Android Toast

Displays information for the short duration of time.


Custom Toast

We are able to customize the toast, such as we can display image on the toast


ToggleButton

It has two states ON/OFF.


CheckBox

Let's see the application of simple food ordering.


AlertDialog

AlertDialog displays a alert dialog containing the message with OK and Cancel buttons.


Spinner

Spinner displays the multiple options, but only one can be selected at a time.


AutoCompleteTextView

Let's see the simple example of AutoCompleteTextView.


RatingBar

RatingBar displays the rating bar.


DatePicker

Datepicker displays the datepicker dialog that can be used to pick the date.


TimePicker

TimePicker displays the timepicker dialog that can be used to pick the time.




ProgressBar

ProgressBar displays progress task.







R.java



Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains resource IDs for all the resources of res/ directory.

If you create any component in the activity_main.xml file, id for the corresponding component is automatically created in this file. This id can be used in the activity source file to perform any action on the component.



Note: If you delete R.jar file, android creates it automatically.







App Menifest



The AndroidManifest.xml file contains information of your package, including components of the application such as activities, services, broadcast receivers, content providers etc.

Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest file presents essential information about your app to the Android system, information the system must have before it can run any of the app's code.

It performs some other tasks also:


  • It is responsible to protect the application to access any protected parts by providing the permissions.
  • It also declares the android api that the application is going to use.
  • It lists the instrumentation classes. The instrumentation classes provides profiling and other informations. These informations are removed just before the application is published etc.
  • This is the required xml file for all the android application and located inside the root directory.




Elements of the AndroidManifest.xml file


The elements used in the above xml file are described below.

<manifest>


manifest is the root element of the AndroidManifest.xml file. It has package attribute that describes the package name of the activity class.

<application>


application is the subelement of the manifest. It includes the namespace declaration. This element contains several subelements that declares the application component such as activity etc.

The commonly used attributes are of this element are icon, label, theme etc.

android:icon represents the icon for all the android application components.

android:label works as the default label for all the application components.

android:theme represents a common theme for all the android activities.

<activity>


activity is the subelement of application and represents an activity that must be defined in the AndroidManifest.xml file. It has many attributes such as label, name, theme, launchMode etc.

android:label represents a label i.e. displayed on the screen.

android:name represents a name for the activity class. It is required attribute.

<intent-filter>


intent-filter is the sub-element of activity that describes the type of intent to which activity, service or broadcast receiver can respond to.

<action>




It adds an action for the intent-filter. The intent-filter must have at least one action element.

<category>


It adds a category name to an intent-filter.



DVM (Dalvik Virtual Machine)



As we know the modern JVM is high performance and provides excellent memory management. But it needs to be optimized for low-powered handheld devices as well.

The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile devices. It optimizes the virtual machine for memory, battery life and performance.

Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.

The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple class files are converted into one dex file.





The javac tool compiles the java source file into the class file.

The dx tool takes all the class files of your application and generates a single .dex file. It is a platform-specific tool.

The Android Assets Packaging Tool (aapt) handles the packaging process.






Saturday, 16 April 2016

Hello Android Example




Create a Project with Android Studio





  • In Android Studio, create a new project:
  • If you don't have a project opened, in the Welcome screen, click New Project.
  • If you have a project opened, from the File menu, select New Project. The Create New Project screen appears.
  • Fill out the fields on the screen, and click Next.It is easier to follow these lessons if you use the same values as shown.
  • Application Name is the app name that appears to users. For this project, use "My First App."
  • Company domain provides a qualifier that will be appended to the package name; Android Studio will remember this qualifier for each new project you create.
  • Package name is the fully qualified name for the project (following the same rules as those for naming packages in the Java programming language). Your package name must be unique across all packages installed on the Android system. You can Edit this value independently from the application name or the company domain
  • Project location is the directory on your system that holds the project files.
  • Under Select the form factors your app will run on, check the box for Phone and Tablet.
  • For Minimum SDK, select API 8: Android 2.2 (Froyo).
  • The Minimum Required SDK is the earliest version of Android that your app supports, indicated using the API level. To support as many devices as possible, you should set this to the lowest version available that allows your app to provide its core feature set. If any feature of your app is possible only on newer versions of Android and it's not critical to the app's core feature set, you can enable the feature only when running on the versions that support it
  • Leave all of the other options (TV, Wear, and Glass) unchecked and click Next.
  • Under Add an activity to <template>, select Blank Activity and click Next.
  • Under Customize the Activity, change the Activity Name to MyActivity. The Layout Name changes to activity_my, and the Title to MyActivity. The Menu Resource Name is menu_my.
  • Click the Finish button to create the project.
  • Your Android project is now a basic "Hello World" app that contains some default files.


    Reference:
    http://developer.android.com/training/basics/firstapp/creating-project.html#Studio


Android Studio




The Official IDE for Android
Android Studio provides the fastest tools for building apps on every type of Android device.

World-class code editing, debugging, performance tooling, a flexible build system, and an instant build/deploy system all allow you to focus on building unique and high quality apps.




Android Studio Overview

Android Studio is the official IDE for Android app development, based on IntelliJ IDEA. On top of IntelliJ's powerful code editor and developer tools, Android Studio offers even more features that enhance your productivity when building Android apps, such as


  1. A flexible Gradle-based build system
  2. Build variants and multiple APK file generation
  3. Code templates to help you build common app features
  4. A rich layout editor with support for drag and drop theme editing
  5. Lint tools to catch performance, usability, version compatibility, and other problems
  6. Code shrinking with ProGuard and resource shrinking with Gradle
  7. Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engin

Reference:
http://developer.android.com/tools/studio/index.html


Android Emulator





Android Emulator is used to run, debug and test the android application. If you don't have the real device, it can be the best way to run, debug and test the application.

It uses an open source processor emulator technology called QEMU.

QEMU (short for Quick Emulator) is a free and open-source hosted hypervisor that performs hardware virtualization (not to be confused with hardware-assisted virtualization).

The emulator tool enables you to start the emulator from the command line. You need to write:

emulator -avd <AVD NAME>






Android Core Building Blocks




Android components


An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, Service etc.

The core building blocks or fundamental components of android are activities, views, intents, services, content providers, fragments and AndroidManifest.xml.


Activity


An activity represents a single screen with a user interface. An application can have one or more activity. For example a contact app shows contact list might be an activity and where we create new contact it might be also other activity.




View


A view is the UI element such as button, label, text field etc. Anything that you see is a view.


Intent


Intent is used to invoke components. It is mainly used to:

Start the service
Launch an activity
Display a web page
Display a list of contacts
Broadcast a message
Dial a phone call etc.



Service


A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface. For example, a service might play music in the background while the user is in a different app, or it might fetch data over the network without blocking user interaction with an activity. Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it.


Content Provider


Content Providers are used to share data between the applications.


Fragment


Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same time.


AndroidManifest.xml


It contains informations about activities, content providers, permissions etc. It is like the web.xml file in Java EE.




Android Virtual Device (AVD)


It is used to test the android application without the need for mobile or tablet etc. It can be created in different configurations to emulate different types of real devices.



Android Architecture




Android Architecture categorized in five parts.


  1. Linux kernel
  2. Native libraries (Middle ware)
  3. Android Runtime
  4. Application Framework
  5. Application.

See figure.





1. Linux kernel



Linux kernel is the heart of android architecture that exists at the root of android architecture. Linux kernel is responsible for device drivers, power management, memory management, device management and resource access.



2. Native Libraries


On the top of Linux kernel, their are Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime library (libc) etc.

The WebKit library is responsible for browser support, SQLite is for database, FreeType for font support, Media for playing and recording audio and video formats.


3. Android Runtime


In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run android application. DVM is like JVM but it is optimized for mobile devices. It consumes less memory and provides fast performance.




4. Android Framework


On the top of Native libraries and android runtime, there is android framework. Android framework includes Android API's such as UI (User Interface), telephony, resources, locations, Content Providers (data) and package managers. It provides a lot of classes and interfaces for android application development.


5. Applications



On the top of android framework, there are applications. All applications such as home, contact, settings, games, browsers are using android framework that uses android runtime and libraries. Android runtime and native libraries are using Linux kernel.

History of Android




The history and versions of android are interesting to know. The code names of android ranges from A to J currently, such as Aestro, Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat, Lollipop and Marshmallow . Let's understand the android history in a one by one.

1. Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States in October, 2003.

2. In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary of Google Incorporation.

3. The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris White and Nick Sears.

4. Originally intended for camera but shifted to smart phones later because of low market for camera only.

5. Android is the nick name of Andy Rubin given by coworkers because of his love to robots.

6. In 2007, Google announces the development of android OS.

7. In 2008, HTC launched the first android mobile.



Android Versions, Codename, API and Distribution





VersionCodenameAPIDistribution
2.2Froyo80.1%
2.3.3 -
2.3.7
Gingerbread102.6%
4.0.3 -
4.0.4
Ice Cream Sandwich152.2%
4.1.xJelly Bean167.8%
4.2.x1710.5%
4.3183.0%
4.4KitKat1933.4%
5.0Lollipop2116.4%
5.12219.4%
6.0Marshmallow234.6%
Source:
http://developer.android.com/about/dashboards/index.html

What is Android




Just we need to know actually what is android?.


Android  is a software package that Linux based operating system for mobile, tablets and computer.

Android OS developed by Google and later the OHA (Open Handset Alliance). Java language is mainly used to write the android code even though other languages can be used.

The goal of android project is to create a successful real-world product that improves the mobile experience for end users.

There are many code names of android such as Marshmallow, Lollipop, Kitkat, Jelly Bean, Ice cream Sandwich, Froyo, Ecliar, Donut etc.



What is Open Handset Alliance (OHA)


It's a consortium of 84 companies such as google, samsung, AKM, synaptics, KDDI, Garmin, Teleca, Ebay, Intel etc.

It was established on 5th November, 2007, led by Google. It is committed to advance open standards, provide services and deploy handsets using the Android Platform.





Features of Android


After learning what is android, let's see the features of android. The important features of android are given below:

1. It is open-source.

2. Anyone can customize the Android Platform.

3. There are a lot of mobile applications that can be chosen by the consumer.

4. It provides many interesting Software and hardware features like Camera, Photo Editing, NFC(Near Field Communication), WI-FI, Sensor, Weather details, Opening screen, Live RSS (Really Simple Syndication) feeds etc.


It provides support for messaging services(SMS and MMS), web browser, storage (SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout etc.





Categories of Android applications


There are many android applications in the market. The top categories are:

Books & Reference
Business
Comics
Communications
Education
Entertainment
Finance
Health and Fitness
Libraries and Demo
Lifestyle
Media and Video
Medical
Music and Audio
New and Magazine
Personalization
Photography
Productivity
Shopping
Social
Sports
Tools
Transportation
Travel and Local
Weather.