Android_Practice
Android_Practice
❖ Source:
Android applications are freely available and can be downloaded from the Web. Following is the list of
software's you will need before you start your Android application programming.
Android SDK
Here last two components are optional and if you are working on Windows machine then these components
make your life easy while doing Java based application development. So let us have a look how to proceed
to set required environment.
Step 1 - Setup Java Development Kit (JDK)
You can download the latest version of Java JDK from Oracle's Java site: Java SE Downloads. You will find
instructions for installing JDK in downloaded files, follow the given instructions to install and configure the
setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java
and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and
installed the JDK in C:\jdk1.6.0_15, you would have to put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15
Alternatively, you could also right-click on My Computer, select Properties, then Advanced, then
Environment Variables. Then, you would update the PATH value and press the OK button. On Linux, if the
SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you would put the following code into
your .cshrc file.
setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH
Alternatively, if you use an Integrated Development Environment (IDE) Eclipse, then it will know
automatically where you have installed your Java.
Step 2 - Setup Android SDK
You can download the latest version of Android SDK from Android official website :
https://developer.android.com/sdk/index.html. If you are installing SDK on Windows machine, then you
will find a installer_rXX-windows.exe, so just download and run this exe which will launch Android SDK
Tool Setup wizard to guide you throughout of the installation, so just follow the instructions carefully.
Finally you will haveAndroid SDK Tools installed on your machine. If you are installing SDK either on Mac OS
or Linux, check the instructions provided along with the downloaded android-sdk_rXX-macosx.zip file for
Mac OS and android-sdk_rXX-linux.tgz file for Linux. This tutorial will consider that you are going to setup
your environment on Windows machine having Windows 7 operating system. So let's launch Android SDK
Manager using the option All Programs > Android SDK Tools > SDK Manager, this will give you following
window:
Once you launched SDK manager , its time to install other required packages. By default it will list
download total 7 packages to be installed, but I will suggest to de-select Documentation for Android SDK
and Samples for
SDK packages to reduce installation time. Next click Install 7 Packages button to proceed, which will
display following dialogue box:
If you agree to install all the packages, select Accept All radio button and proceed by clicking Install button.
Now let SDK manager do its work and you go, pick up a cup of coffee and wait until all the packages are
installed. It may take some time depending on your internet connection. Once all the packages are
installed, you can close SDK manager using top-right cross button.
Step 3 - Setup Eclipse IDE
All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have
latest version of Eclipse installed on your machine.
To install Eclipse IDE, download the latest Eclipse binaries from http://www.eclipse.org/downloads/. Once
you downloaded the installation, unpack the binary distribution into a convenient location. For example in
C:\eclipse on windows, or /usr/local/eclipse on Linux and finally set PATH variable appropriately. Eclipse
can be started by executing the following commands on windows machine, or you can simply double click
on eclipse.exe
%C:\eclipse\eclipse.exe
$/usr/local/eclipse/eclipse
After a successful startup, if everything is fine then it should display following result:
dialogue box.
Now use Add button to add ADT Plugin as name and https://dl-ssl.google.com/android/eclipse/ as the
location. Then click OK to add this location, as soon as you will click OK button to add this location, Eclipse
starts searching for the plug-in available the given location and finally lists down the found plugins.
Now select all the listed plug-ins using Select All button and click Next button which will guide you ahead
to install Android Development Tools and other required plugins.
Step 5 - Create Android Virtual Device
To test your Android applications you will need a virtual Android device. So before we start writing our
code, let us create an Android virtual device. Launch Android AVD Manager using Eclipse menu
optionsWindow > AVD Manager> which will launch Android AVD Manager. Use New button to create a
new Android Virtual Device and enter the following information, before clicking Create AVD button.
If your AVD is created successfully it means your environment is ready for Android application
development. If you like, you can close this window using top-right cross button. Better you re-start your
machine and once you are done with this last step, you are ready to proceed for your first Android
example but before that we will see few more important concepts related to Android Application
Development.
Experiment 2
❖ Source:
The first step is to create a simple Android Application using Eclipse IDE. Follow the option File -> New ->
Project and finally select Android New Application wizard from the wizard list. Now name your application
as HelloWorld using the wizard window as follows:
Next, follow the instructions provided and keep all other entries as default till the final step. Once your
project is created successfully, you will have following project screen:
1 src This contains the .java source files for your project. By default, it includes an
MainActivity.java source file having an activity class that runs when your app is launched
using the app icon
.
2 gen This contains the .R file, a compiler-generated file that references all the resources
found in your project. You should not modify this file.
3
bin This folder contains the Android package files .apk built by the ADT during the build
process and everything
else needed to run an Android application.
4
res/drawable-hdpi This is a directory for drawable objects that are designed for high-
density screens.
5
res/layout This is a directory for files that define your app's user interface.
6
res/values This is a directory for other various XML files that contain a collection of
resources, such as strings and colors definitions.
7
AndroidManifest.xml This is the manifest file which describes the fundamental
characteristics of the app and defines each of its components.
Following section will give a brief overview few of the important application files.
The Main Activity File
The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately
gets converted to a Dalvik executable and runs your application. Following is the default code generated by
the application wizard for Hello World! application:
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity
{
}
}
Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder.
TheonCreate() method is one of many methods that are fi red when an activity is loaded.
The Manifest File
Whatever component you develop as a part of your application, you must declare all its
components in a manifest file called AndroidManifest.xml which ressides at the root of the application
project directory. This file works as an interface between Android OS and your application, so if you do not
declare your component in this file, then it will not be considered by the OS. For example, a default
manifest file will look like as following file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
</activity>
</application>
</manifest>
package com.example.helloworld;
public final class R
{
public static final class attr
{
}
}
public static final class id
{
public static final int menu_settings=0x7f080000;
}
public static final class layout
{
public static final int activity_main=0x7f030000;
}
public static final class menu
{
public static final int activity_main=0x7f070000;
}
{
public static final int AppTheme=0x7f060000;
}
}
android:layout_height="match_parent" >
<TextView>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world" tools:context=".MainActivity" />
</RelativeLayout>
This is an example of simple RelativeLayout which we will study in a separate chapter. The TextView
is an Android control used to build the GUI and it have various attribuites like
android:layout_width,android:layout_height etc which are being used to set its width and height etc. The
@string refers to the strings.xml file located in the res/values folder. Hence, @string/hello_world refers to
the hello string defined in the strings.xml fi le, which is "Hello World!".
Running the Application
Let's try to run our Hello World! application we just created. I assume you had created your AVD
while doing environment setup. To run the app from Eclipse, open one of your project's activity files and
click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator win
Experiment 3
Source:
(A) AndroidManifest.xml
The AndroidManifest.xml file is where your global settings are made. If you are an
ASP.NET developer, you can think of AndroidManifest.xml as Web.config and
Global.asax rolled into one. (If you are not an ASP.NET developer, this means that
AndroidManifest.xml is a place for storing settings.) AndroidManifest.xml will include
such settings as application permissions, Activities, and intent filters.
The standard AndroidManifest.xml file should contain the following information:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.golu.map1.test">
<application>
<uses-library android:name="android.test.runner" />
</application>
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.golu.map1"
android:handleProfiling="false"
android:functionalTest="false"
As you create future applications, you will be adding information to this file. Notice
that the package name you supplied is listed here, as well as the action that your Activity
will handle.
(A) i. Edit the manifest and change min sdk and target sdk of application.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.golu.map1.test">
<application>
<uses-library android:name="android.test.runner" />
</application>
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.golu.map1"
android:handleProfiling="false"
android:functionalTest="false"
android:label="Tests for com.example.golu.map1"/>
</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" //First Activity
android:label="@string/title_activity_main" >
</activity>
<service android:name=".MyService" /> //Second Activity
</application>
</manifest>
Experiment 4
Source:
a. Create application with Basic Views (Textview, Button, ListView)
Step 1
You will use Eclipse IDE to create an Android application and name it as HelloWorld
under a package com.example.helloworld as explained in the Hello World Example
chapter.
Step2
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class CustomListActivity extends Activity {
/** Called when the activity is first created. */
ListView lv;
LayoutInflater inflator;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listView1);
BaseAdapter bs = new BaseAdapter() {
return vw;
}
};
}
}
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="0dp"
android:layout_marginTop="15dp"
android:text="Medium Text"
android:textSize="15dp" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="25dp"
android:text="Button" />
</LinearLayout>
Aim: Create application which can share link on facebook using Facebook sdk..
Source:
• Create new android project [File >> New >> Android Application Project] with project name
FBShareActivity
• Enter the package name and activity name you have entered in Facebook developer console while
creating Facebook Application
• Choose Minimum Required SDK, Target SDK and Compile with (Choose latest SDKs to make sure
Facebook SDK will work without any issues). Confused on choosing these options? Take a look
at Minimum Required SDK – Target SDK – Compile With post.
• Click Next button and finally click ‘Finish’ to create project
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;
public class MainActivity extends Activity {
// Create, automatically open (if applicable), save, and restore the
// Active Session in a way that is similar to Android UI lifecycles.
private UiLifecycleHelper uiHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// To maintain FB Login session
uiHelper = new UiLifecycleHelper(this, null);
uiHelper.onCreate(savedInstanceState);
}
@Override
public void onError(FacebookDialog.PendingCall pendingCall,
Exception error, Bundle data) {
Toast.makeText(getApplicationContext(), "Error OccurednMost Common
Errors:n1. Device not connected to Internetn2.Faceboook APP Id is not changed in Strings.xml",
Toast.LENGTH_LONG).show();
}
@Override
public void onComplete(
FacebookDialog.PendingCall pendingCall, Bundle data) {
Toast.makeText(getApplicationContext(),"Done!!",Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
}
Aim: Create application which can share link on facebook using Facebook sdk..
Source:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/re
s/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertica
l_margin"
android:paddingLeft="@dimen/activity_horizontal
_margin"
android:paddingRight="@dimen/activity_horizonta
l_margin"
android:paddingTop="@dimen/activity_vertical_m
argin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Simple Android Toast Example"
/>
<Button
android:id="@+id/showToast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Toast Message"
android:layout_marginTop="16dp"
android:layout_below="@+id/textView"/>
</RelativeLayout>
package
com.viralandroid.androidtoast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.showToast);
// Show toast message when button is clicked
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"This is my
toast message",Toast.LENGTH_LONG).show();// Set your own
toast message
}
});
}
@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);
}
}
Output:
Experiment 7
Aim: Create application which can share link on facebook using Facebook sdk..
Source:
File : res/layout/main.xml
24.
File : res/layout/main2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Step3: Activities
File : App1Activity.java
package com.mkyong.android;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
Button button;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
button.setOnClickListener(new OnClickListener() {
@Override
startActivity(intent);
});
File : App2Activity.java
package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Step4.
Experiment 8
Aim: Create application which can share link on facebook using Facebook sdk..
Source:
Step 3:
Complete code for AndroidManifest.xml File :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.broadcastreceiver"
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.androidexample.broadcastreceiver.BroadcastNewSms"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<receiver android:name="com.androidexample.broadcastreceiver.IncomingSms">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
</manifest>
try {
if (bundle != null) {
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
}
}
}
Experiment 9
Aim: Create application which can share link on facebook using Facebook sdk..
Source:
package com.tutorialspoint.myapplication;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
@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) {
checkInternetConenction();
downloadImage("http://www.tutorialspoint.com/green/images/logo.png");
}
});
}
new Thread() {
public void run() {
InputStream in = null;
try {
in = openHttpConnection(url);
bitmap = BitmapFactory.decodeStream(in);
Bundle b = new Bundle();
b.putParcelable("bitmap", bitmap);
msg.setData(b);
in.close();
}
try {
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return in;
}
@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);
}
}
<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="UI Animator Viewer"
android:id="@+id/textView"
android:textSize="25sp"
android:layout_centerHorizontal="true" />
<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_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:textColor="#ff36ff15"
android:textIsSelectable="false"
android:textSize="35dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="76dp" />
</RelativeLayout>
<resources>
<string name="app_name">My Application</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>
<activity
android:name=".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>
Output: