0% found this document useful (0 votes)
6 views

Android_Practice

The document outlines the steps to set up an Android development environment, including the installation of Java JDK, Android SDK, and Eclipse IDE. It details the creation of an Android project using Eclipse, including the structure of the project files such as the Manifest file, Main Activity, and resource files. Additionally, it covers how to edit the Manifest file to include various application settings and permissions.

Uploaded by

vibhaphaye025
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Android_Practice

The document outlines the steps to set up an Android development environment, including the installation of Java JDK, Android SDK, and Eclipse IDE. It details the creation of an Android project using Eclipse, including the structure of the project files such as the Manifest file, Main Activity, and resource files. Additionally, it covers how to edit the Manifest file to include various application settings and permissions.

Uploaded by

vibhaphaye025
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Experiment 1

❖ Aim: Download and setup Android Environment.

❖ 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.

Java JDK5 or JDK6

Android SDK

Eclipse IDE for Java Developers (optional)

Android Development Tools (ADT) Eclipse Plugin (optional)

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

setenv JAVA_HOME /usr/local/jdk1.6.0_15

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

Eclipse can be started by executing the following commands on Linux machine:

$/usr/local/eclipse/eclipse

After a successful startup, if everything is fine then it should display following result:

Step 4 - Setup Android Development Tools (ADT) Plugin


This step will help you in setting Android Development Tool plugin for Eclipse. Let's start with launching
Eclipse and then, choose Help > Software Updates > Install New Software. This will display the following

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

❖ Aim: Using the Development environment


a. Create a new Project using wizard

❖ 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:

Anatomy of Android Application


Before you run your app, you should be aware of a few directories and files in the Android project:

s.no Folder, File & Description

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
{

public void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override public boolean onCreateOptionsMenu(Menu menu)


{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;

}
}

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" >

<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" android:label="@string/title_activity_main" > <intent-
filter> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>

</activity>
</application>
</manifest>

Here <application>...</application> tags enclosed the components related to the application.


Attributeandroid:icon will point to the application icon available under res/drawable-hdpi. The application
uses the image named ic_launcher.png located in the drawable folders The <activity> tag is used to specify
an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and
the android:label attributes specifies a string to use as the label for the activity. You can specify multiple
activities using <activity> tags. The action for the intent filter is named android.intent.action.MAIN to
indicate that this activity serves as the entry point for the application. The category for the intent-filter is
namedandroid.intent.category.LAUNCHER to indicate that the application can be launched from the
device's launcher icon. The @string refers to the strings.xml file explained below. Hence,
@string/app_name refers to theapp_name string defined in the strings.xml fi le, which is "HelloWorld".
Similar way, other strings get populated in the application. Following is the list of tags which you will use in
your manifest file to specify different Android application components:

<activity>elements for activities

<service> elements for services

<receiver> elements for broadcast receivers

<provider> elements for content providers


The Strings File
The strings.xml file is located in the res/values folder and it contains all the text that your
application uses. For example, the names of buttons, labels, default text, and similar types of strings go
into this file. This file is responsible for their textual content. For example, a default strings file will look like
as following file:
<resources>
<string name="app_name">HelloWorld </string>

<string name="hello_world">Hello world!</string>


<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
The R File
The gen/com.example.helloworld/R.java file is the glue between the activity Java files
likeMainActivity.java and the resources like strings.xml. It is an automatically generated file and you should
not modify the content of the R.java file. Following is a sample of R.java file:
/* AUTO-GENERATED FILE. DO NOT MODIFY. *
* This class was automatically generated by the
* aapt tool from the resource data it found. It

* should not be modified by hand.


*/

package com.example.helloworld;
public final class R

{
public static final class attr
{
}

public static final class dimen


{
public static final int padding_large=0x7f040002;
public static final int padding_medium=0x7f040001;

public static final int padding_small=0x7f040000;


}
public static final class drawable
{
public static final int ic_action_search=0x7f020000;
public static final int ic_launcher=0x7f020001;

}
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 class string


{
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050001;

public static final int menu_settings=0x7f050002;


public static final int title_activity_main=0x7f050003;
}
public static final class style

{
public static final int AppTheme=0x7f060000;
}
}

The Layout File


The activity_main.xml is a layout file available in res/layout directory, that is referenced by your
application when building its interface. You will modify this file very frequently to change the layout of
your application. For your "Hello World!" application, this file will have following content related to default
layout:
<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" >
<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

Aim: XML Files


a. AndroidManifest.xml
a.i. Edit the manifest and change min sdk and target sdk of application.
a.ii. Add main activity entries in manifest.
a.iii. Add second activity entries in manifest.
a.iv. Add Entries for Service, Broadcast receivers.
a.v. Add uses permissions for reading files, internet, camera.

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">

<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="24" />

<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>

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">

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="23" />

<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>

Changed to the min sdk 15 to 8 and target sdk 24 to 23.

(A).ii. Add main activity entries in manifest.


iii. Add second activity entries in manifest.
Following will the modified content of AndroidManifest.xml file. Here we have added <service.../>
tag to include our service:

<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" >

<intent-filter> <action android:name="


android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>

</activity>
<service android:name=".MyService" /> //Second Activity
</application>
</manifest>
Experiment 4

Aim: 4. Creating User Interface


a. Create application with Basic Views (Textview, Button, ListView)
b. Create application with different Layouts (Linear, Relative, Frame)
c. Create application to handle and respond on click using Click Listeners

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

Modify the detault content of res/layout/activity_main.xml file to include ListView


content with the self explanatory a

Following is the content of the modified main activity


filesrc/com.example.helloworld/MainActivity.java. This file can include each of the
fundamental lifecycle methods. ttributes.
package com.example.helloworld;

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() {

public View getView(int position, View convertView, ViewGroup parent) {

// TODO Auto-generated method stub


View vw = inflator.inflate(R.layout.list_items, null);
TextView tv = (TextView)findViewById(R.id.textView1);
Button btn = (Button)findViewById(R.id.button1);

return vw;
}

public long getItemId(int position) {

// TODO Auto-generated method stub


return 0;
}

public Object getItem(int position) {

// TODO Auto-generated method stub


return null;
}

public int getCount() {


// TODO Auto-generated method stub
return 2;
}

};
}
}

Following will be the content of res/layout/activity_main.xml file:


<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" tools:context=".ListActivity" >
<ListView>
android:id="@+id/country_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

<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>

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">HelloWorld</string>
<string name="action_settings">Settings</string>
</resources>

Following will be the content of res/layout/activity_listview.xml file:


<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
Let's try to run our modified Hello World! application we just modified. I assume you had
created yourAVD 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 window:
Experiment 5

Aim: Create application which can share link on facebook using Facebook sdk..
Source:

Step 1: Create Android Application Project

• 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

Step 2: Add Facebook SDK as dependency project


Right click on the project you created >> Choose Properties >> Choose Android Tab >> Go to lower part of
the dialog >> Click on Add button >> Select FacebookSDK Project.
Troubleshooting Tips:
1. You should configure FacebookSDK in your workspace, that means import FacebookSDK library project into
your workspace before your try to add it as dependency project.
2. FacebookSDK library project and the Android application you just created should be under same
Workspace.
Step 3: Design screen
3. Open activity_main.xml and replace it with below code.
4. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
5. xmlns:tools="http://schemas.android.com/tools"
6. android:layout_width="match_parent"
7. android:layout_height="match_parent"
8. android:background="@drawable/bg_gradient"
9. android:orientation="vertical"
10. android:paddingBottom="@dimen/activity_vertical_margin"
11. android:paddingLeft="@dimen/activity_horizontal_margin"
12. android:paddingRight="@dimen/activity_horizontal_margin"
13. android:paddingTop="@dimen/activity_vertical_margin"
14. tools:context="com.prgguru.example.MainActivity" >
15.
16. <Button
17. android:id="@+id/postStatusUpdateButton"
18. android:layout_width="fill_parent"
19. android:layout_height="wrap_content"
20. android:layout_marginTop="25dp"
21. android:background="@drawable/bg_button_rounded"
22. android:onClick="postStatusUpdate"
23. android:text="Post Status Update"
24. android:textColor="@color/white" />
25.
26. <Button
27. android:id="@+id/shareButton"
28. android:layout_width="fill_parent"
29. android:layout_height="wrap_content"
30. android:layout_marginTop="25dp"
31. android:background="@drawable/bg_button_rounded"
32. android:onClick="shareTutorialonFB"
33. android:text="Share this tutorial on FB"
34. android:textColor="@color/white" />
35.
36. </LinearLayout>
37.

Step 4: MainActivity.java – Main Class


Open MainActivity.java and replace it with below code.
Each line of code is commented well, if you still have any doubt or question 2 Comments it.
package com.prgguru.example;

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);
}

// When Post Status Update button is clicked


public void postStatusUpdate(View v){
// Pass null as parameter for setLink method to post status update
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this)
.setLink(null)
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}

// When Share this tutorial on FB button is clicked


public void shareTutorialonFB(View v){
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this)
.setLink("http://programmerguru.com/android-tutorial/getting-started-with-the-facebook-
sdk-for-android/")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
// After Facebook Dialog is closed
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

uiHelper.onActivityResult(requestCode, resultCode, data,


new FacebookDialog.Callback() {

@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();
}
}

Step 5: Add the Facebook app ID into your project


Add your Facebook app ID into your project, open up the strings.xml file in the res/values folder of your
project and add below value:
<string name="app_id">YOUR_FACEBOOK_APP_ID</string>

Step 6: Add Meta Data to application tag in AndroidManifest


As shown below, add a ‘Meta Data’ item called com.facebook.sdk.ApplicationId, with a value of the app_id
string you just configured:
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/app_id" />

Step 7: Add permission in AndroidManifest.xml


Add Internet permission in AndroidManifest:
<uses-permission android:name="android.permission.INTERNET" />
Output:
Experiment 6

Aim: Create application which can share link on facebook using Facebook sdk..
Source:

Step 1: Create a new project


Step2: Modified code of activity layout file looks like this.
res/layout/activity_main.xml

<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>

Step3: Modified code of Java Activity looks like this.


src/MainActivity.java

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:

Step 1: Create a new project

Step2: Create following two XML layout files in “res/layout/” folder :

1. res/layout/main.xml – Represent screen 1


2. res/layout/main2.xml – Represent screen 2

File : res/layout/main.xml

3. <?xml version="1.0" encoding="utf-8"?>


4. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
5. android:id="@+id/linearLayout1"
6. android:layout_width="fill_parent"
7. android:layout_height="fill_parent"
8. android:orientation="vertical" >
9.
10. <TextView
11. android:id="@+id/textView1"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:text="I'm screen 1 (main.xml)"
15. android:textAppearance="?android:attr/textAppearanceLarge" />
16.
17. <Button
18. android:id="@+id/button1"
19. android:layout_width="fill_parent"
20. android:layout_height="wrap_content"
21. android:text="Click me to another screen" />
22.
23. </LinearLayout>

24.

File : res/layout/main2.xml

<?xml version="1.0" encoding="utf-8"?>

<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:text="I'm screen 2 (main2.xml)"

android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Step3: Activities

Create two activity classes :

1. AppActivity.java –> main.xml


2. App2Activity.java –> main2.xml

To navigate from one screen to another screen, use following code :

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;

public class AppActivity extends Activity {

Button button;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

addListenerOnButton();

public void addListenerOnButton() {

final Context context = this;

button = (Button) findViewById(R.id.button1);

button.setOnClickListener(new OnClickListener() {
@Override

public void onClick(View arg0) {

Intent intent = new Intent(context,


App2Activity.class);

startActivity(intent);

});

File : App2Activity.java

package com.mkyong.android;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

public class App2Activity extends Activity {


Button button;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main2);

Step4.
Experiment 8

Aim: Create application which can share link on facebook using Facebook sdk..
Source:

Step 1: Create a new project


Step 2: 1. Declare receiver in AndroidManifest
<receiver android:name=".IncomingSms">
<intent-filter>

<action android:name="android.provider.Telephony.SMS_RECEIVED" />


</intent-filter>
</receiver>

3. Give read SMS permission in AndroidManifest


<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>

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" />

<category android:name="android.intent.category.LAUNCHER" />

</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>

Step 4: Complete code for IncomingSms.java file :


public class IncomingSms extends BroadcastReceiver {

// Get the object of SmsManager


final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context, Intent intent) {

// Retrieves a map of extended data from the intent.


final Bundle bundle = intent.getExtras();

try {

if (bundle != null) {

final Object[] pdusObj = (Object[]) bundle.get("pdus");

for (int i = 0; i < pdusObj.length; i++) {

SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);

String phoneNumber = currentMessage.getDisplayOriginatingAddress();

String senderNum = phoneNumber;


String message = currentMessage.getDisplayMessageBody();

Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);

// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: "+ senderNum + ", message: " + message, duration);

toast.show();

} // end for loop


} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);

}
}
}
Experiment 9

Aim: Create application which can share link on facebook using Facebook sdk..
Source:

Step 1: Create a new project


Step 2: Here is the content of src/MainActivity.java.

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;

public class MainActivity extends ActionBarActivity {


private ProgressDialog progressDialog;
private Bitmap bitmap = null;
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) {
checkInternetConenction();
downloadImage("http://www.tutorialspoint.com/green/images/logo.png");
}
});
}

private void downloadImage(String urlStr) {


progressDialog = ProgressDialog.show(this, "", "Downloading Image from " + urlStr);
final String url = urlStr;

new Thread() {
public void run() {
InputStream in = null;

Message msg = Message.obtain();


msg.what = 1;

try {
in = openHttpConnection(url);
bitmap = BitmapFactory.decodeStream(in);
Bundle b = new Bundle();
b.putParcelable("bitmap", bitmap);
msg.setData(b);
in.close();
}

catch (IOException e1) {


e1.printStackTrace();
}
messageHandler.sendMessage(msg);
}
}.start();
}

private InputStream openHttpConnection(String urlStr) {


InputStream in = null;
int resCode = -1;

try {
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();

if (!(urlConn instanceof HttpURLConnection)) {


throw new IOException("URL is not an Http URL");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
resCode = httpConn.getResponseCode();

if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}

catch (MalformedURLException e) {
e.printStackTrace();
}

catch (IOException e) {
e.printStackTrace();
}
return in;
}

private Handler messageHandler = new Handler() {


public void handleMessage(Message msg) {
super.handleMessage(msg);
ImageView img = (ImageView) findViewById(R.id.imageView);
img.setImageBitmap((Bitmap) (msg.getData().getParcelable("bitmap")));
progressDialog.dismiss();
}
};

private boolean checkInternetConenction() {


// get Connectivity Manager object to check connection
ConnectivityManager connec
=(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);

// Check for network connections


if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
return true;
}else if (
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED ) {
Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
return false;
}
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);
}
}

Step3: Here is the content of activity_main.xml

<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>

Step4: Here is the content of Strings.xml.

<resources>
<string name="app_name">My Application</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>

Step5: Here is the content of AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorialspoint.myapplication" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<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:

You might also like