How to Create Facebook App ID

Step1: Go to facebook developer site and login. Here is facebook developer link https://developers.facebook.com/apps open this and login to developer account.

How to Create Facebook App ID

Step2: Click on “My App” tab and select “create new app”.

Step3: Choose your platform “Android”
How to Create Facebook App ID

Step4: Enter your App name and click on “Create New Facebook App ID”.

How to Create Facebook App ID

Step5: Choose your category and click on “Create App ID”.

How to Create Facebook App ID

Step6: Enter your package name and your default Activity class name.

How to Create Facebook App ID

Step6: If your app already published on Google Play Store than it will find otherwise ignore this message and click on “Use this package name”.

How to Create Facebook App ID

Step7: Add your development hash key and release hash key.

How to Create Facebook App ID

Step8: Creating new app is finished

How to Create Facebook App ID

Step9: Click on “Skip Quick Start”

How to Create Facebook App ID

Step10: Here is your app id

How to Create Facebook App ID

How To Upload App on Google Play Store

To upload an app on google play store you need these things:

  • 1.Signed Apk
  • 2.Short Description (max 80 words)
  • 3.Long Description
  • 4.App Icon (size 512X512).
  • 5.App Screenshots
    • a.For Mobile (min. 2 screenshots).
    • b.For 7 inch Tablet (min. 1 Screenshots)
    • c.For 10 inch Tablet(min. 1 Screenshots)
  • 6.Features Graphics image (size 1024X500)

Step1. Now login to your google developer console https://play.google.com/apps/publish/

Step2. Click on “Add new application”.

How To Upload App on Google Play Store

Step3. Enter your app title and select your app language.

How To Upload App on Google Play Store

Step4. Click on “Upload Apk” select your signed apk.

How To Upload App on Google Play Store

Step5. After upload apk, enter all details of “STORE LISTING”.

Enter all required fields like

Short Description

Long Description

How To Upload App on Google Play Store

Add screenshots as above mentions for “Mobile” and “Tablets”

Also add “Hi-res icon” (App Icon)

How To Upload App on Google Play Store

Add app “Category” , “Contact Details” and “Privacy Policy”.

How To Upload App on Google Play Store

Now click on “Save Draft” on top of screen.

Step6. Create “Content Rating” for this enter your email id and select your app category.

Enter all required fields based on your app development and their contents.

Step7. Finally under “Price and Distribution” select distributed country list

How To Upload App on Google Play Store

Then under “CONSENT” check mark “content guidelines” and “US export laws”.

How To Upload App on Google Play Store

Step8. Save your details and click on “Publish App” at top of the screen.

How To Upload App on Google Play Store

After submission of your app it will show “Pending Submission”.

Now it will take some hours to verify all details by google and your app will in market if every this is right and if you are not using any copyright image or contents.

How to get Google Admob Ad ID

Step1: Open below link and sign in into admob. https://www.google.com/admob/

How to get Google Admob Ad ID

Step2: Click on “Monetize a New App”

How to get Google Admob Ad ID

Step3: “Click on Add Your App Manually”

Step4: Enter your app name , select your platform and click on “Add app”.


How to get Google Admob Ad ID

Step5: “Select ad format and name ad unit” Your can choose which type if ad do you want. Banner / Interstitial

How to get Google Admob Ad ID

Step6: Enter Ad unit name and click on “Save”

How to get Google Admob Ad ID

Step7: Copy “Ad unit ID: ca-app-pub-7335882925318194/12327XXXXX”

How to get Google Admob Ad ID

Use this ID to generate your Ads

How to add admob in android project

Import Eclipse Project into Android Studio

Suppose you are working on a project on eclipse, which have external libraries and jars files inside your project. And you have to switch on Android Studio than it’s not like to eclipse that import all project and libraries than add them directly into project. Android studio use gradle for dependency of libraries and jar file.

Here is a simple example of whole process.

Import Eclipse Project into Android Studio

Here you can see there is three project is present in which RoundShapeActivity is your main project and other two is library project.

Import Eclipse Project into Android Studio

Step1: Right Click on your main project , select “export” than select “Generate Gradle Build Files”.

Import Eclipse Project into Android Studio

Step2: Select project to generate gradle build file.

Import Eclipse Project into Android Studio

Step3: Now finish this process.

Import Eclipse Project into Android Studio

Go to your workspace and check there will be gradle build files are generated.

Import Eclipse Project into Android Studio

Step4: Open your Android Studio and select “import project” . import your root folder of project, where gradle build file are generated.

Import Eclipse Project into Android Studio

Step5: If your version of the Android Gradle plug-in () is not match than fix it or download by clicking on below link on android studio.

Import Eclipse Project into Android Studio

Finally you will get screen like this.

Import Eclipse Project into Android Studio

Step6: Now run your project.

Note: some time gradle give error for supported libraries
In this case open build.gradle of your project and add this line.

dependencies {
compile fileTree(dir: ‘libs’, include: ‘*.jar’, exclude: ‘android-support-*.jar’)
}

Now run your project.

How to remove Admob

Step1: Right Click on project and open “Properties”

Step2: Rremove “Google play service libary” from project.

Step3: Remove this line from “menifest.xml”

  <activity
       android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

Step4: Delete “banner_adview.xml” from “layout”.

Step5: Remove this line from all xml file in which you are getting errors

<include
       android:id="@+id/ad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/include1"
        layout="@layout/banner_adview" />  

Step6: Open every Activity Class and remove this line

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;

public InterstitialAd interstitial;

//** Admob Code */
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest request = new AdRequest.Builder().build();
adView.loadAd(request);
interstitial = new InterstitialAd(getBaseContext());
interstitial.setAdUnitId(getResources().getString(
R.string.interstitial_id));
interstitial.loadAd(request);

if it’s present


@Override
public void onBackPressed() {
if (interstitial.isLoaded()) {
interstitial.show();
}
super.onBackPressed();
}

Step7: Clean your project and run.

How to add admob

How to Send Data to Other App in Android Studio

Android defines several actions, including ACTION_SEND which, as you can probably guess, indicates that the intent is sending data from one activity to another, even across process boundaries. To send data to another activity, all you need to do is specify the data and its type, the system will identify compatible receiving activities and display them to the user.

Send Text Content

Android provides intent library to share data between activities an application in order to use it as share intent, we have to specify the type of the share intent to ACTION_SEND.
Intent shareIntent=new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
Next thing you need to is to define the type of data to pass, and then pass the data.
shareIntent.setType(“text/plain”);

shareIntent.PutExtra(Intent.EXTRA_TEXT, “Helloo from mobilemerit”);
startActivity(Intent.createChooser(shareIntent, “Share”));
if you call Intent.createChooser(), passing it your Intent object, it returns a version of your intent that will always display the chooser.

Send Binary Content

Binary data is shared using the ACTION_SEND action combined with setting the appropriate MIME type and placing the URI to the data in an extra named EXTRA_STREAM. This is commonly used to share an image but can be used to share any type of binary content:

Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
    shareIntent.setType("image/jpeg");
    startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));

Create a new project in Android Studio

File – New Android Project

How to Send Data to Other App in Android Studio
How to Send Data to Other App in Android Studio

MainActivity.java

public class MainActivity extends ActionBarActivity {
    Button button ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.bButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareIntent();

            }
        });

    }

    private void shareIntent() {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("Text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "Heloo from mobilemerit");
        startActivity(Intent.createChooser(shareIntent, "Share"));
    }
    @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;
    }

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"
    tools:context=".MainActivity">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Button to share somthing"
    android:id="@+id/bButton"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

</RelativeLayout>

How to Send Data to Other App in Android Studio

How to use Media player in Android Studio

Create a new project in Android Studio

File – New Android Project

How to use Media player in Android Studio
How to use Media player in Android Studio

MediaPlayer:-Android providing Media Player Class to access android in built mediaplayer service like playing audio, video etc.

In order to use MediaPlayer, we have to call static method create() of this class. This method return and instance of MediaPlayer class
MediaPlayer mediaplayer = MediaPlayer.create(this, R.raw.song);

The second parameter is the name of the song that you want to play. You have to make a new folder under “res” folder which name is raw and place the music file into it.

Once you have to created the mediaplayer object you can call some method to start or stop the music. These methods are:-

mediaPlayer.start();
mediaPlayer.pause();

layout of the main activity

lactivity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/songName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="songName" />

    <ImageView
        android:id="@+id/mp3Icon"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="30dp"
        android:background="#ffffff"
        android:padding="30dp"
        android:src="@drawable/music" />

    <TextView
        android:id="@+id/songDuration"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="songDuration" />

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="30dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/btn_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="backforward"
            android:src="@android:drawable/ic_media_rew" />

        <ImageButton
            android:id="@+id/btn_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="pause"
            android:src="@android:drawable/ic_media_pause" />

        <ImageButton
            android:id="@+id/btn_Play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="play"
            android:src="@android:drawable/ic_media_play" />

        <ImageButton
            android:id="@+id/btn_forword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="forward"
            android:src="@android:drawable/ic_media_ff" />
    </LinearLayout>

</LinearLayout>

Createing MainActivity

MainActivity.java

import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.os.Handler;
import java.util.concurrent.TimeUnit;

public class MainActivity extends ActionBarActivity {
    private MediaPlayer mediaPlayer;
    private TextView songName, songDuration;
    private SeekBar seekBar;
    private double timeStart = 0, finalTime = 0;
    private int forwardTime = 2000, backwardTime = 2000;
    private Handler durationHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        songName = (TextView) findViewById(R.id.songName);
        songDuration = (TextView) findViewById(R.id.songDuration);
        mediaPlayer = MediaPlayer.create(this, R.raw.sample_song);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        songName.setText("Song.mp3");
        seekBar.setMax((int) finalTime);
        seekBar.setClickable(false);
    }
    private Runnable updateSeekBarTime = new Runnable() {
        public void run() {
            timeStart = mediaPlayer.getCurrentPosition();
            seekBar.setProgress((int) timeStart);
            double timeRemaining = finalTime - timeStart;
            songDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
            durationHandler.postDelayed(this, 100);
        }
    };
    public void play(View view) {
        mediaPlayer.start();
        timeStart = mediaPlayer.getCurrentPosition();
        seekBar.setProgress((int) timeStart);
        durationHandler.postDelayed(updateSeekBarTime, 100);
    }
    public void pause(View view) {
        mediaPlayer.pause();
    }
    public void forward(View view) {
        if ((timeStart + forwardTime) <= finalTime) {
            timeStart = timeStart - backwardTime;
            mediaPlayer.seekTo((int) timeStart);
        }
    }
    public void backforward(View view) {
        //check if we can go back at backwardTime seconds after song starts
        if ((timeStart - backwardTime) > 0) {
            timeStart = timeStart - backwardTime;
            mediaPlayer.seekTo((int) timeStart);
        }
    }
    @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) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mobilemerit.com.mediaplayer" >
    <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>

How to use Media player in Android Studio

How to use Android Widgets in Android Studio

Create a new project in Android Studio

File – New Android Project.
How to use Android Widgets in Android Studio
How to use Android Widgets in Android Studio

What a is Widget

A widget is a small gadget or control of your android appliaction palced on the home screen. Widget can be veru handy as the allow to put your favourite application on the screen in order to quickly access them.

Create a Android Widgets

Right click on src/ package-New-Widget-app widget

Creating AppWidgetProvider in XML

This is used to describe the metadata for an app Widget, such as the app Widget’s layout, update frequency, and the AppWidget provider class. This is always defined as XML file.

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialKeyguardLayout="@layout/new_app_widget"
    android:initialLayout="@layout/new_app_widget"
    android:minHeight="40dp"
    android:minWidth="40dp"
    android:previewImage="@drawable/example_appwidget_preview"
    android:resizeMode="horizontal|vertical"
    android:updatePeriodMillis="86400000"
    android:widgetCategory="home_screen">
    </appwidget-provider>

Create the App widget Layout

<TextView
        android:id="@+id/appwidget_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_margin="8dp"
        android:background="#09C"
        android:contentDescription="@string/appwidget_text"
        android:text="@string/appwidget_text"
        android:textColor="#ffffff"
        android:textSize="24sp"
        android:textStyle="bold|italic" />

Use AppWidget Provider class

public class NewAppWidget extends AppWidgetProvider {
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        final int N = appWidgetIds.length;
        for (int i = 0; i < N; i++) {
            updateAppWidget(context, appWidgetManager, appWidgetIds[i]);
        }
    }


    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
        views.setTextViewText(R.id.appwidget_text, widgetText);
 // Create an Intent to launch MainActivity
        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        views.setOnClickPendingIntent(R.id.appwidget_text,pendingIntent);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

AndroidManifest.xml

We need to register the app widget in your application manifest file. To do this, you will use the tag. This block of XML should be placed inside the application tag in application manifest.
The receiver name is the name of your app widget provider class implementation.

<receiver android:name=".NewAppWidget" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/new_app_widget_info" />
        </receiver>

Android Services

Introduction to service

  • A service is a application component that run in the background to perform long running operation without needing to interact with the user.
  • Service can run in the background indefinitely ,even if component that started the service is destroyed.
  • A service run in the main thread of the application instance.It does’t create its own thread.
  • Service always performing a single operation and stop itself one intended task is completed.

Service can essentially take two forms:

  • Started service-A service is started when the application is (like Activity) start it by calling startService() method.It is stopped by stopService() method.The service can stop itself by calling the stopSelf() method.
  • Bound service-A service is bound when an application component bind to its by calling bindService() method. The client can unbind the service by calling the unBindService() method.

Android Service Life Cycle

Android Services

onStartCommand()

This method is called when the service be started,by calling startService().onece this method executes, the service is started and can run in the background indefinitely

onBind()

This metod is called when another component wants to bind with the service by calling bindService().

onUnbind()

This method is called when the all clients have disconnected from a particular interface.

onCreate()

This method is called while the service is first created.Here all the service initialization is done.This method is never called again.

onDestroy()

The system call this method when the service is no longer used and being destroyed.

Creating Android Service

Right click on src/package – New – Service-Service

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"
    tools:context=".MainActivity">
    <Button
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:text="Start service"
        android:id="@+id/button"
        android:onClick="startService"/>
    <Button
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:text="Stop Service"
        android:id="@+id/button2"
        android:layout_alignParentEnd="true"
        android:onClick="stopService"/>
</RelativeLayout>

MyService.java

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
    public MyService() {
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
     
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service stop", Toast.LENGTH_LONG).show();
    }

MainActivity.java

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void startService(View view){
        startService(new Intent(MainActivity.this,MyService.class));
    }
    public void stopService(View view){
        stopService(new Intent(MainActivity.this,MyService.class));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {    
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {     
        int id = item.getItemId();      
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Start Android Service

Intent intent= new Intent (this, MyService.class);

startService(intent);

Stop Running Android Service

A service must be stopped itself by calling stopSelf() method onece it is finish execuation. You can also stopped a service yourself by calling stopService() method.

stopService() method will call onDestroy() callback in your service.

Android Services

How to use Progress Dialog in Android

Using of Progress Dialog

progress bar are used to show progress of task e.g. downloading file,analyzing status of work etc.

//ProgressDialog progress = new ProgressDialog(this);

Now you can set some properties of this dialog.

progressDialog = new ProgressDialog(this);
                progressDialog.setMessage("Downloading...");
                progressDialog.setTitle("Your Title");
                progressDialog.setCancelable(true);
                progressDialog.setIndeterminate(true);
                progressDialog.show();	

activity_main.xml

<Button
       android:layout_width="200dp"
       android:layout_marginLeft="60dp"
       android:text="Progress Dialog"
       android:id="@+id/button"
       android:layout_height="wrap_content"
       android:layout_marginTop="170dp"
       android:layout_alignParentTop="true"
       />	

MainActivity.java

import android.app.ProgressDialog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends ActionBarActivity {
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //   progressDialog=new ProgressDialog(MainActivity.this);
        Button btn_start_progress = (Button) findViewById(R.id.button);
        btn_start_progress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Downloading...");
                progressDialog.setTitle("Your Title");
                progressDialog.setCancelable(true);
                progressDialog.setIndeterminate(true);
                progressDialog.show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}			

How to use Progress Dialog in Android

How to Create Fragment in Android

Create a new project in Android Studio

File – New Android Project

How to Create Fragment in Android
How to Create Fragment in Android

What is a Fragment

  • A Fragment is a part of activity.Fragment represents a portion of user interface or an operation that runs witin an avtivity.
  • A single activity can contain multiple fragment and many fragments can be reused in many different activities.
  • A fragment has its own layout and its own behavior with its own lifecycle callbacks.
  • Fragment were added to the Android API in Honeycomb version(API 11).

Fragment Life cycle

When a fragment gets created, it goes through the following state.

How to Create Fragment in Android

oncreate()
onAttache()
onCreate()
onCreateView()
onActivityCreated()

When the fragment becomes visible,it goes through these state.

onStart()
onResume()

When the fragment goes into the background mode,it goes through theses state.

onPause()
onStop()

When the fragment is destroyed, it goes to the following states.

onDestroyView()
onDestroy()
onDetach()

How to use Fragment

Performing Fragment Transactions

FragmentManager  fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
                .replace(R.id.container, new fragment(position ))
                .commit();
				
				

How to create Fragment Class

Right click on src/ package-New-Fragment-Fragment(Blank)

Fragment_fragment_one_xml
<FrameLayout 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"
    tools:context="mobilemerit.com.fragmentexample.FragmentOne">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="@string/hello_blank_fragment_one" />

</FrameLayout>

FragmentOne.java

public class FragmentOne extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";

    // TODO: Rename and change types and number of parameters
    public static FragmentOne newInstance(int position) {
        FragmentOne fragment = new FragmentOne();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, position);
        fragment.setArguments(args);
        return fragment;
    }

    public FragmentOne() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_one, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached
                (getArguments().getInt(ARG_PARAM1));
    }
}

How to Create Fragment in Android
How to Create Fragment in Android

How To Show Alert Dialog in Android

Create a new project in Android Studio

File – New Android Project

How To Show Alert Dialog in Android
How To Show Alert Dialog in Android

Dialogs

A dialog is a small window. if you wanted to ask the user about taking a decision between yes or no in response of any particular action taken by the user.

you need to make an object of AlertDialogBuilder which an inner class of AlertDialog.

Android alert dialog with three button

AlertDialog.Builder alertdialog = new AlertDialog.Builder(MainActivity.this);
                alertdialog.setTitle("Your Title");
                alertdialog.setMessage("You want to Delete").setCancelable(false)

                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "You Clicked on no", Toast.LENGTH_LONG).show();
                            }
                        }).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.this.finish();
                    }
                })
                        .setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "You Clicked on cancel", Toast.LENGTH_LONG).show();
                            }
                        });
                               alertdialog.show();

            }
        });

Android alert dialog with two button

AlertDialog.Builder alertdialog = new AlertDialog.Builder(MainActivity.this);
                alertdialog.setTitle("Your Title");
                alertdialog.setMessage("You want to Delete").setCancelable(false)

                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "You Clicked on no", Toast.LENGTH_LONG).show();
                            }
                        }).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.this.finish();
                    }
                });
                    alertdialog.show();

            }
        });

How To Show Alert Dialog in Android
How To Show Alert Dialog in Android

How to use Shared Preferences in Android

Download APK Download Source Code Contact Us

Create a new project in Android Studio

File – New Android Project

How to use Shared Preferences in Android
How to use Shared Preferences in Android

Shared Preferences

Shared Preferences is allow you to save and retrive data in the form of key, value pair.You can use sharedpreferences to save any primitive data,booleans,floats,ints,longs and string.

Use Shared Preferences

getSharedPreferences()- Return sharedPreferences instance poiting to the file that contains the values of preferences. 
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);  

You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will recieve it in an editor object.

public static final String USER_DETAILS_PREFS = "user_details_prefs";
    private static final String NAME = "name";
public static String getName(Context context) {
        SharedPreferences sp = context.getSharedPreferences(
                USER_DETAILS_PREFS, Activity.MODE_PRIVATE);
        return sp.getString(NAME, "");
    }
public static void setUserDetail(Context context, String name) {
SharedPreferences sf = context.getSharedPreferences(
                    USER_DETAILS_PREFS, Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sf.edit();
            editor.putString(NAME, name);
        editor.commit();
}
getPreferences()- Use this from an Activity if you need to use only one shared preference file for the activity.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

Deleting key value from sharedpreferences

SharedPreferences sf = context.getSharedPreferences(
                My_PREFS, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sf.edit();
editor.remove(“key_name1”);
editor.remove(“key_name2”);
editor.commit(); 

Clear all data from sharedPreferences

editor.clear();
editor.commit();
How to use Shared Preferences in Android
How to use Shared Preferences in Android
How to use Shared Preferences in Android

Download APK Download Source Code Contact Us

How to Create DataBase in Android

Download APK Download Source Code Contact Us

Create a new project in Android Studio

File – New Android Project

How to Create DataBase in Android

How to Create DataBase in Android

Using of DataBaseHelper Class

Once the projected is created create a new class in your project src directory and name it as DataBaseHendler.java(Right click on src/package – New – Class)

Now extend your DatabaseHandler.java class from SQLiteOpenHelper.

public class DataBaseHendler extends SqLiteOpenHelper {

After extends your class from SqLiteOpenHelper you need to override two method onCreate() and onUpgrade.

onCreate():-These is where we need to write create table statements. This is called when database is created.

onUpgrade():-This method is called when database is upgraded like modifying the table structure, adding constraints to database .

Create DataBaseHelper Class
Right click on package Name – New – Java Class

For Ex:-

public class DataBaseHelper extends SQLiteOpenHelper {
    // Database version name
    private static final int DATABASE_VERSION = 1;
    // Database name
    private static final String DATBASE_NAME = "regForm.db";

      public static final String TABLE_NAME = "user";
      public static final String USER_ID = "_id";
     public static final String NAME = "name";
     public static final String EMAIL = "email";

    public DataBaseHelper(Context context) {
        super(context, DATBASE_NAME, null, DATABASE_VERSION);
    }

    //Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
String CREATE_USER_TABLE = "create table " + TABLE_NAME
                + " ( " + USER_ID + " integer  primary key autoincrement,"
                + NAME + " TEXT,"
                + EMAIL + " TEXT,"
db.execSQL(CREATE_USER_TABLE);    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

Inserting new Record in the Table

To Insert a new Record in Table we need to create an Object of ContentValues class and put the Values in this like:

 // Assign value for each row
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getAddress()); // Contact Address
    // Insert the row into your table
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}

Reading Row

For Ex:

How to Create DataBase in Android

Deleting Record

deleteContact() will delete single contact from database.
   deleteContact()
public void deleteContact(Contact contact){
SqLiteDatabase db=this.getWriteableDatabase();
 Db.delete(TABLE_CONTACTS, KEY_ID + “ ?”, new String [] { String.valueof(contact.getid)});
Db.close();
}
How to Create DataBase in Android
How to Create DataBase in Android
How to Create DataBase in Android

Download APK Download Source Code Contact Us

How to make an app WebView in android (with source code)

Download APK Download Source Code Contact Us

Step1:­ Create new project in Android Studio.

How to make an app WebView in android
How to make an app WebView in android

What is WebView?

WebView is a view that dispaly web page inside your application. You can also specify HTML
string and can show it inside your application using WebView.

Step 2:­ You must add the internet permissions to your AndroidManifest file.

How to make an app WebView in android

step 3:­ Adding a WebView to your Application.

<WebView> element to your xml layout file.

Ex:­<?xml version="1.0" encoding="utf­8"?>

<WebView xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/webview"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

/>

Step 4:­ Accessing the WebView from code.

How to make an app WebView in android

Step 5:­ Loading the url into the WebView.

Load Web page in the WebView,use loadurl().
EX:­WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");

How to make an app WebView in android

Step:6­ Enabling JavaScript in the WebVIew.

By default the Android WebView component has JavaScript disabled. You can enable through the WebSetting attached to your WebView.

Ex:­WebView myWebView = (WebView) findViewById(R.id.webview);

WebSettings webSettings = myWebView.getSettings();

webSettings.setJavaScriptEnabled(true);

setMinimumFontSize(int size):­ Set the minimum font size. The default is 8.

webSettings.setMinimumFontSize(10);

setMediaPlaybackRequiresGesture(boolean require):­ Set whether the WebView requires a user

gesture to play media. The default is true.

webSettings. setMediaPlaybackRequiresGesture();

setTextZoom(int textZoom):­ Set the text zoom of the page in percent. The default is 100.

webSettins.setTextZoom(150);

Step:7­ Handling Page Navigation.

When the user click a link in the web page loaded into the WebView.the default behaviour is to load that URL of the link in the system Android browser.

To open links clicked by the user, simply provide a WebViewClient for your WebView, using

setWebViewClient().

Ex:­WebView myWebView = (WebView) findViewById(R.id.webview);

myWebView.setWebViewClient(new WebViewClient());

private class MyWebViewClient extends WebViewClient {

@Override

public boolean shouldOverrideUrlLoading(WebView webView, String url) {

return false;

}

}

How to make an app WebView in android

Download APK Download Source Code Contact Us

How To Get Parse App Key and Client Key

Before you start to generate Parse APP_KEY and CLIENT_KEY did you know what is Parse? Ok take a overview of Parse than we will start.

What is Parse??

Parse.com provides a backend service to developers. If your mobile or desktop app requires a backend on the internet, then Parse is one of the options you can choose.

I first came across the service a few months ago and noted that they provide SDKs that let your apps running on various devices connect up to the backend it provides. They provide SDKs for devices running iOS, Android, Windows (Phone) 8, OS X and Javascript. ok now start generating Parse KEY.

Step1: SignUp in to Parse.com, here is a link for signup into parse https://www.parse.com/#signup.

How To Get Parse App Key and Client Key

Step2: Enter Your App Name and click on “Create App”

How To Get Parse App Key and Client Key

Step3: After creating app you will get you Application Key.

How To Get Parse App Key and Client Key
If you can not find your application and client key than go to “Dashboard” and click on “Select an App”
How To Get Parse App Key and Client Key
How To Get Parse App Key and Client Key

Step4: Now click on Setting and than Key here you can get every key that is related to your app

How To Get Parse App Key and Client Key

Step5: Here you can get your Application Key and Client Key.

How To Get Parse App Key and Client Key

How to integrate Facebook Api in Android

Before you start to generate Facebook App id. Take a look on facebook development.

Facebook allows you to obtain a token to access Facebook’s API on behalf of someone using your app. You can use this feature in place of building your own account system or to add Facebook services to your existing accounts.The Facebook SDK for Android provides methods to implement Facebook Login for your app. And to access this feature into your app you need facebook app id.

Now start to generate facebbok id , you should need a facebook account as a developer or you can use your personal account also.

Step1: Goto facebook developer site and login.

Here is facebook developer link https://developers.facebook.com/apps open this and login to developer account.

How to integrate Facebook Api in Android

Step2: click on “Add a New App” and than select your app platform, here we are using Android so click on “Android”.

How to integrate Facebook Api in Android

Step3: Now click on “Create App Id” enter your app details and finally click on ”Create App Id”

How to integrate Facebook Api in Android

Step4: Your Facebook App Id is generated, copy this app id and used for your app development.

How to integrate Facebook Api in Android

Step5: If you need facebook app secret key than click on “show” button and you will get your secret key.

Step6: Goto to https://developers.facebook.com/docs/android and download facebook api.

Step6: After download facebook sdk extract it. You will get facebook api project import it to you workspace.

How to integrate Facebook Api in Android

Step7: Create a project name ImageSharing and add facebooksdk lib into your project from properties. And write this codes.

Write this code in MainActivity.java

Write  this code in MainActivity.java
package com.example.imagesharing;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
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.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;

import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;

public class MainActivity extends Activity {
	private UiLifecycleHelper uiHelper;
	FacebookDialog shareDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		showHashKey(this);
		uiHelper = new UiLifecycleHelper(this, null);
		uiHelper.onCreate(savedInstanceState);

		// to share photo=================

		Bitmap bm = BitmapFactory.decodeResource(getResources(),
				R.drawable.ic_launcher);
		List<Bitmap> image = new ArrayList<Bitmap>();
		image.add(bm);
		if (FacebookDialog.canPresentShareDialog(getApplicationContext(),
				FacebookDialog.ShareDialogFeature.PHOTOS)) {
			FacebookDialog shareDialog = new FacebookDialog.PhotoShareDialogBuilder(
					this).addPhotos(image).build();
			uiHelper.trackPendingDialogCall(shareDialog.present());
		} else {
		}
	}

	@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) {
						Log.e("Activity",
								String.format("Error: %s", error.toString()));
					}

					@Override
					public void onComplete(
							FacebookDialog.PendingCall pendingCall, Bundle data) {
						Log.i("Activity", "Success!");
					}
				});
	}

	@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();
	}
//this function is to get hash key of your project.
//you can check it in log.
	public static void showHashKey(Context context) {
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					"com.example.imagesharing",
					PackageManager.GET_SIGNATURES); // Your package name here
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				Log.i("KeyHash:",
						Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (NameNotFoundException e) {
		} catch (NoSuchAlgorithmException e) {
		}
	}

}
Open string.xml in value folder and write this line
<string name="app_id">1533995260210845</string>
Now finally in your manifest.xml write this codes.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.imagesharing"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.imagesharing.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.LoginActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <meta-data android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />
        <provider android:authorities="com.facebook.app.NativeAppCallContentProvider1533995260210845"
                  android:name="com.facebook.NativeAppCallContentProvider"
                  android:exported="true"/>
    </application>

</manifest>

Run your app now you will get direct facebook page to share image on facebook.com

Add Admob in Android App

Step1:

Create new Project in eclipse.

Add Admob in Android App

Step2:

import Google Play Services library into your workspace.

What is Google Play Services

Step3:

add Google Play Services library into your project.

Right Click on project than open “property” window.

Click on “Android” and add library.

Add Admob in Android App

Step4:

Add your Banner and Interstitial id in “strings.xml”

Example:

<string name="banner_id">ca-app-pub-7335882925318194/**********</string>
<string name="interstitial_id">ca-app-pub-7335882925318194/**********</string>  

Add Admob in Android App

Step5:

Give permission for internet inside “manifest.xml”.

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

Copy and paste these lines into you manifest.xml under tag.

 

                android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

        <meta -data android:name="com.google.android.gms.version"
                   android:value="@integer/google_play_services_version" />

Add Admob in Android App

Step6:

Create a xml file inside “layout” folder which is under “res” folder. Give file name as “banner_adview.xml”.

Copy and paste these codes into “banner_adview.xml”

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

  <com .google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/banner_id"
        android:visibility="visible"></com>

</linearlayout>

Step7:

include “banner_adview.xml” into your “activity_main.xml” by adding these lines into “activity_main.xml”

<include layout="@layout/banner_adview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></include>

Add Admob in Android App

Step8:

create “InterstitialAd” variable into “MainActivity.java”.

private InterstitialAd interstitial;
add these lines to integrate banner adview into “onCreate()”
AdView adView = (AdView) this.findViewById(R.id.adView);
  		AdRequest request = new AdRequest.Builder().build();
  		adView.loadAd(request);
  		interstitial = new InterstitialAd(getBaseContext());
  		interstitial.setAdUnitId(getResources().getString(R.string.interstitial_id));
  		interstitial.loadAd(request);

and finally add these line for interstitial ad on back pressed button.
@Override
	public void onBackPressed() {
		if(interstitial.isLoaded()){
			interstitial.show();
		}
		super.onBackPressed();
	}

Add Admob in Android App

Run your project and check you have successfully added Admob into your app.

Add Admob in Android App

What is Google Play Services

The Google Play services APK contains the individual Google services and runs as a background service in the Android OS. You interact with the background service through the client library and the service carries out the actions on your behalf. An easy-to-use authorization flow is also provided to gain access to the each Google service, which provides consistency for both you and your users.
The Google Play services APK is delivered through the Google Play Store, so updates to the services are not dependent on carrier or OEM system image updates. In general, devices running Android 2.3 (Gingerbread) or later and have the Google Play Store app installed receive updates within a few days. This allows you to use the newest APIs in Google Play services and reach most of the devices in the Android ecosystem (devices older than Android 2.3 or devices without the Google Play Store app are not supported).
How to import Google Play Services into workspace

Step1: open “Android SDK Manager”

What is Google Play Services

Step2: check did you install google play service or not, if it’s not than install is first.

What is Google Play Services
Here I already installed so it’s showing here as installed, you first install this and goto next step

Step3: after installation of google play service, check it. It will store in your android sdk bundle Here is path for google play service \your directory..\adt-bundle-windows-x86_64-20130514\sdk\extras\google

Step4: now come to eclipse and click on “File” than “import”. A window will be open here you have to select google play service lib. Select as it is in image

What is Google Play Services

Step5: now click on check box

What is Google Play Services
And you successfully imported google play service into your workspace.
Now it is ready to use.

Set Alarm In Android From Excel Date Tutorial

This tutorial will tell to that how to read data from excel file and how to set alarm in android. To read date and time we are using excel file then we will set alarm at this date and time and we will learn how to show notification for this alarm. For this you need..

1. JExcelApi

For reading and writing we need a library. JExcelApi gives all the power of Microsoft Excel: workbooks, formulas, full spreadsheet control. Easy to mix Java logic and Excel capabilities.

2. Android Alarm Manager

Many a times we want some task to be performed at some later time in future. For Example: In SMS Scheduler we want a SMS to be send at some later time, or Task Reminder in which we want to be reminded about a task at a particular time, to implement all these things we use AlramManager class.

AlarmManager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been
registered for it is broadcast or service by the system, automatically starting the target application if it is not already running.

3. Notification in Android

android.app.Notification.Builder is a builder class for Notification objects. Provides a convenient way
to set the various fields of a Notification and generate content views using the platform’s
notification layout template. If your app supports versions of Android as old as API level 4, you can
instead use NotificationCompat.Builder, available in the Android Support library.

Concepts

Reading Spreadsheets
JExcelApi can read an Excel spreadsheet from a file stored on the local filesystem or from some input
stream. The first step when reading a spreadsheet from a file or input stream is to create a
Workbook. The code fragment below illustrates creating a workbook from a file on the local
filesystem.
import java.io.File;
import java.util.Date;
import jxl.*;

Workbook workbook = Workbook.getWorkbook(new File(“myfile.xls”));
Once you have accessed the workbook, you can use this to access the individual sheets. These are
zero indexed – the first sheet being 0, the second sheet being 1, and so on.
Sheet sheet = workbook.getSheet(0);
Once you have a sheet, you can then start accessing the cells. You can retrieve the cell’s contents as
a string by using the convenience method getContents(). In the example code below, A1 is a text cell,
B2 is numerical value and C2 is a date. The contents of these cells may be accessed as follows
Cell a1 = sheet.getCell(0,0);
Cell b2 = sheet.getCell(1,1);
Cell c2 = sheet.getCell(2,1);
String stringa1 = a1.getContents();
String stringb2 = b2.getContents();
String stringc2 = c2.getContents();
// Do stuff with the strings etc

The demo programs CSV.java and XML.java use the convenience method getContents() in order to
output the spreadsheet contents.
When you have finished processing all the cells, use the close() method. This frees up any allocated
memory used when reading spreadsheets and is particularly important when reading large
spreadsheets.
// Finished – close the workbook and free up memory
workbook.close();

Setting alarm

To set the alarm we are using method “getSysytemService(ALARM_SERVICE)” of the class
AlarmManager.
To use the method we have create an instance “alarmManager” of the class AlarmManager.
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Set pendingIntent which will perform the assigned task will be invoked by Trigger.
Intent intent = new Intent(this,TaskNotify.class);PendingIntent pendingIntent = PendingIntent.getService(this.getApplicationContext(),
REQUEST_CODE,intent,0);
Setting time and task for alarm
alarmManager.set(AlarmManager.RTC_WAKEUP,TimeInMilliSec,pendingIntent);

Example:

Insert two file in your project
1. Date.xls in assets folder
image 1
2. Athan.mp3 in raw folder under res folder
image 2
And make sure you excel file data cells will be in same like
image 3

Whatever date and time you want you can enter but cell field will be same as above mention.

MainActivity.java

package com.example.excelandalarm;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import android.app.Activity;import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView text;
private List<Task> taskList;
private AlarmManager alarmManager;
public static final String EXTRA_ID = "id";
public static final int REQUEST_BROAD_CODE = 376650;
public static final int REQUEST_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (TaskNotifyService.mp != null) {
TaskNotifyService.mp.release();
}
taskList = new ArrayList<Task>();
text = (TextView) findViewById(R.id.textview);
readDateFromExcel();
for (Task task : taskList) {setAlarm(task);
text.setText("Alarm is set");
}
}
private void readDateFromExcel() {
try {
Workbook workbook = Workbook.getWorkbook(getAssets().open(
"date.xls"));
Sheet sheet = workbook.getSheet(0);
for (int i = 1; i < sheet.getRows(); i++) {
Cell cell1 = sheet.getCell(1, i);
Cell cell2 = sheet.getCell(2, i);
String date = (cell1.getContents() + " " + cell2.getContents());
if (!date.trim().contentEquals("")) {
Task task = new Task();
task.setDate(date);
taskList.add(task);
}
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}public void setAlarm(Task task) {
Date date1 = new Date();
Date date2 = new Date(task.getDate());
if (date2.after(date1)) {
startAlert(task);
}
}
public void startAlert(Task task) {
Intent intent = new Intent(MainActivity.this, TaskNotifyService.class);
PendingIntent pendingIntent = PendingIntent.getService(
this.getApplicationContext(),
new Random().nextInt(REQUEST_BROAD_CODE), intent, 0);
Date date = new Date(task.getDate());
Calendar virtual = Calendar.getInstance();
virtual.set(Calendar.DATE, date.getDate());
virtual.set(Calendar.MONTH, date.getMonth());
virtual.set(Calendar.YEAR, date.getYear() + 1900);
virtual.set(Calendar.HOUR_OF_DAY, date.getHours());
virtual.set(Calendar.MINUTE, date.getMinutes());
virtual.set(Calendar.SECOND, 0);
virtual.set(Calendar.MILLISECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, virtual.getTimeInMillis(),
pendingIntent);
}}

Task.java


package com.example. excelandalarm;
public class Task {
String title, date, note;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getNote() {
return note;
}
public void setNote(String note) {this.note = note;
}
}

TaskNotifyService.java

package com.example. excelandalarm;
import java.util.Random;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
public class TaskNotifyService extends Service {
public static MediaPlayer mp = new MediaPlayer();;
Runnable runnable;
Context c;
public static final int ID = 36589;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stubreturn null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
c = getBaseContext();
player();
sendNotification();
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
public void sendNotification() {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(c)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle("Alarm")
.setContentText("AYN SOFT");
Intent resultIntent = new Intent(c, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(c);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) c
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(new Random().nextInt(ID), mBuilder.build());
}
private void player() {
try {
if (mp != null) {
mp.release();
}
Vibrator vibrator = (Vibrator) c
.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
mp = MediaPlayer.create(c, R.raw.athan);
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}

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"
 tools:context=".MainActivity" > 
<TextView 
 android:id="@+id/textview"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>
</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example. excelandalarm"
 android:versionCode="1"
 android:versionName="1.0" >
 <uses-sdk
 android:minSdkVersion="8"
 android:targetSdkVersion="17" />
 <uses-permission android:name="android.permission.VIBRATE" />
 <application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name="com.example.tutorialproject.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>
 <service android:name="com.example.tutorialproject.TaskNotifyService"/>
 </application>
</manifest>

image 4 Set Alarm In Android From Excel Date Tutorial

Geofences

Geofencing combines awareness of the user’s current location with awareness of nearby features, defined as the user’s proximity to locations that may be of interest. To mark a location of interest, you specify its latitude and longitude. To adjust the proximity for the location, you add a radius. The latitude, longitude, and radius define a geofence. You can have multiple active geofences at one time.

Location Services treats a geofences as an area rather than as a points and proximity. This allows it to detect when the user enters or exits a geofence. For each geofence, you can ask Location Services to send you entrance events or exit events or both. You can also limit the duration of a geofence by specifying an expiration duration in milliseconds. After the geofence expires, Location Services automatically removes it.

Request Geofence Monitoring

The first step in requesting geofence monitoring is to request the necessary permission

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

Check for Google Play Services

GooglePlayServicesUtil.isGooglePlayServicesAvailable(), which returns one of the integer result codes listed in the API reference documentation. If you encounter an error, callGooglePlayServicesUtil.getErrorDialog() to retrieve localized dialog that prompts users to take the correct action, then display the dialog in a DialogFragment. The dialog may allow the user to correct the problem, in which case Google Play services may send a result back to your activity. To handle this result, override the method onActivityResult()

To use geofencing, start by defining the geofences you want to monitor. Although you usually store geofence data in a local database or download it from the network, you need to send a geofence to Location Services as an instance of Geofence, which you create with Geofence.Builder. Each Geofence object contains the following information:

Latitude, longitude, and radius

Define a circular area for the geofence. Use the latitude and longitude to mark a location of interest, and then use the radius to adjust how close the user needs to approach the location before the geofence is detected. The larger the radius, the more likely the user will trigger a geofence transition alert by approaching the geofence. For example, providing a large radius for a geofencing app that turns on lights in the user’s house as the user returns home might cause the lights to go on even if the user is simply passing by.

Expiration time

How long the geofence should remain active. Once the expiration time is reached, Location Services deletes the geofence. Most of the time, you should specify an expiration time, but you may want to keep permanent geofences for the user’s home or place of work.

Transition type

Location Services can detect when the user steps within the radius of the geofence (“entry”) and when the user steps outside the radius of the geofence (“exit”), or both.

Geofence ID

A string that is stored with the geofence. You should make this unique, so that you can use it to remove a geofence from Location Services tracking.

A geofencing app needs to read and write geofence data to persistent storage. You shouldn’t use Geofenceobjects to do this; instead, use storage techniques such as databases that can store groups of related data.

public class MainActivity extends FragmentActivity {
...
/**
* A single Geofence object, defined by its center and radius.
*/
public class SimpleGeofence {
// Instance variables
private final String mId;
private final double mLatitude;
private final double mLongitude;
private final float mRadius;
private long mExpirationDuration;
private int mTransitionType;
/**
* @param geofenceId The Geofence's request ID
* @param latitude Latitude of the Geofence's center.
* @param longitude Longitude of the Geofence's center.
* @param radius Radius of the geofence circle.
* @param expiration Geofence expiration duration
* @param transition Type of Geofence transition.
*/
public SimpleGeofence(
String geofenceId,
double latitude,
double longitude,
float radius,
long expiration,
int transition) {
// Set the instance fields from the constructor
this.mId = geofenceId;
this.mLatitude = latitude;
this.mLongitude = longitude;

Create Geofence objects

The following snippet uses the SimpleGeofence and SimpleGeofenceStore classes gets geofence data from the UI, stores it in SimpleGeofence objects, stores these objects in a SimpleGeofenceStore object, and then creates Geofence objects:

public class MainActivity extends FragmentActivity {
...
/*
* Use to set an expiration time for a geofence. After this amount
* of time Location Services will stop tracking the geofence.
*/
private static final long SECONDS_PER_HOUR = 60;
private static final long MILLISECONDS_PER_SECOND = 1000;
private static final long GEOFENCE_EXPIRATION_IN_HOURS = 12;
private static final long GEOFENCE_EXPIRATION_TIME =
GEOFENCE_EXPIRATION_IN_HOURS *
SECONDS_PER_HOUR *
MILLISECONDS_PER_SECOND;
...
/*
* Handles to UI views containing geofence data
*/
// Handle to geofence 1 latitude in the UI
private EditText mLatitude1;
// Handle to geofence 1 longitude in the UI
private EditText mLongitude1;
// Handle to geofence 1 radius in the UI
private EditText mRadius1;
// Handle to geofence 2 latitude in the UI
private EditText mLatitude2;
// Handle to geofence 2 longitude in the UI
private EditText mLongitude2;
// Handle to geofence 2 radius in the UI
private EditText mRadius2;

In addition to the List of Geofence objects you want to monitor, you need to provide Location Services with the Intent that it sends to your app when it detects geofence transitions.

Define a Intent for geofence transitions

The Intent sent from Location Services can trigger various actions in your app, but you should not have it start an activity or fragment, because components should only become visible in response to a user action. In many cases, an IntentService is a good way to handle the intent.

private PendingIntent getTransitionPendingIntent() {
// Create an explicit Intent
Intent intent = new Intent(this,
ReceiveTransitionsIntentService.class);
/*
* Return the PendingIntent
*/
return PendingIntent.getService(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}

Send the monitoring request

Sending the monitoring request requires two asynchronous operations. The first operation gets a location client for the request, and the second makes the request using the client. In both cases, Location Services invokes a callback method when it finishes the operation.

public class MainActivity extends FragmentActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnAddGeofencesResultListener {
...
}

Start the request process

Next, define a method that starts the request process by connecting to Location Services. Mark this as a request to add a geofence by setting a global variable. This allows you to use the callbackConnectionCallbacks.onConnected() to add geofences and to remove them, as described in succeeding sections.

public void addGeofences() {
// Start a request to add geofences
mRequestType = ADD;/*
* Test for Google Play services after setting the request type.
* If Google Play services isn't present, the proper request
* can be restarted.
*/
if (!servicesConnected()) {
return;
}
/*
* Create a new location client object. Since the current
* activity class implements ConnectionCallbacks and
* OnConnectionFailedListener, pass the current activity object
* as the listener for both parameters
*/
mLocationClient = new LocationClient(this, this, this)
// If a request is not already underway
if (!mInProgress) {
// Indicate that a request is underway
mInProgress = true;
// Request a connection from the client to Location Services
mLocationClient.connect();
} else {
/*
* A request is already underway. You can handle
* this situation by disconnecting the client,
* re-setting the flag, and then re-trying the
* request.
*/
}
}

Send a request to add the geofences

In your implementation of ConnectionCallbacks.onConnected(), call LocationClient.addGeofences(). Notice that if the connection fails, onConnected() isn’t called, and the request stops.

@Override
private void onConnected(Bundle dataBundle) {
...
switch (mRequestType) {
case ADD :
// Get the PendingIntent for the request
mTransitionPendingIntent =
getTransitionPendingIntent();
// Send a request to add the current geofences
mLocationClient.addGeofences(
mCurrentGeofences, pendingIntent, this);
...
}
}

Check the result returned by Location Services

When Location Services invokes your implementation of the callback method onAddGeofencesResult(), indicating that the request is complete, examine the incoming status code.

@Override
public void onAddGeofencesResult(
int statusCode, String[] geofenceRequestIds) {
// If adding the geofences was successful
if (LocationStatusCodes.SUCCESS == statusCode) {
/*
* Handle successful addition of geofences here.
* You can send out a broadcast intent or update the UI.
* geofences into the Intent's extended data.
*/
} else {
// If adding the geofences failed
/*
* Report errors here.
* You can log the error using Log.e() or update
* the UI.
*/
}
// Turn off the in progress flag and disconnect the client
mInProgress = false;
mLocationClient.disconnect();
}

Handle disconnections

In some cases, Location Services may disconnect from the activity recognition client before you calldisconnect()

@Override
public void onDisconnected() {
// Turn off the request flag
mInProgress = false;
// Destroy the current location client
mLocationClient = null;
}

Handle Geofence Transitions

When Location Services detects that the user has entered or exited a geofence, it sends out the Intentcontained in the PendingIntent you included in the request to add geofences.

This Intent isDefine an IntentService

The following snippet shows how to define an IntentService that posts a notification when a geofence transition occurs. When the user clicks the notification, the app’s main activity appears:

public class ReceiveTransitionsIntentService extends IntentService {
...
/**
* Sets an identifier for the service
*/
public ReceiveTransitionsIntentService() {
super("ReceiveTransitionsIntentService");
}
/**
* Handles incoming intents
*@param intent The Intent sent by Location Services. This
* Intent is provided
* to Location Services (inside a PendingIntent) when you call
* addGeofences()
*/
@Override
protected void onHandleIntent(Intent intent) {
// First check for errors
if (LocationClient.hasError(intent)) {
// Get the error code with a static method
int errorCode = LocationClient.getErrorCode(intent);
// Log the error
Log.e("ReceiveTransitionsIntentService",
"Location Services error: " +
Integer.toString(errorCode));
/*
* You can also send the error code to an Activity or
* Fragment with a broadcast Intent
*/
/*
* If there's no error, get the transition type and the IDs
* of the geofence or geofences that triggered the transition
*/
} else {
// Get the type of transition (entry or exit)
int transitionType =
LocationClient.getGeofenceTransition(intent);
// Test that a valid transition was reported
if (
(transitionType == Geofence.GEOFENCE_TRANSITION_ENTER)
||
(transitionType == Geofence.GEOFENCE_TRANSITION_EXIT)
) {
List <Geofence> triggerList =
getTriggeringGeofences(intent);
String[] triggerIds = new String[geofenceList.size()];
for (int i = 0; i < triggerIds.length; i++) {
// Store the Id of each geofence
triggerIds[i] = triggerList.get(i).getRequestId();
}

Specify the IntentService in the manifest

To identify the IntentService to the system, add a element to the app manifest. For example:

<service
android:name="com.example.android.location.ReceiveTransitionsIntentService"
android:label="@string/app_name"
android:exported="false">
</service>

Stop Geofence Monitoring

To stop geofence monitoring, you remove the geofences themselves. You can remove a specific set of geofences or all the geofences associated with a PendingIntent. The procedure is similar to adding geofences. The first operation gets a location client for the removal request, and the second makes the request using the client. The callback methods that Location Services invokes when it has finished removing geofences are defined in the interface LocationClient.OnRemoveGeofencesResultListener. Declare this interface as part of your class definition, and then add definitions for its two methods:

onRemoveGeofencesByPendingIntentResult()

Callback invoked when Location Services finishes a request to remove all geofences
made by the methodremoveGeofences(PendingIntent,
LocationClient.OnRemoveGeofencesResultListener).

onRemoveGeofencesByRequestIdsResult(List,
LocationClient.OnRemoveGeofencesResultListener)

Callback invoked when Location Services finished a request to remove a set of
geofences, specified by their geofence IDs, by the
method removeGeofences(List,
LocationClient.OnRemoveGeofencesResultListener).

Examples of implementing these methods are shown in the next snippets.

Remove all geofences

Since removing geofences uses some of the methods you use to add geofences, start by defining another request type:

public class MainActivity extends FragmentActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnAddGeofencesResultListener {
...
// Enum type for controlling the type of removal requested
public enum REQUEST_TYPE = {ADD, REMOVE_INTENT}
...
}

Start the removal request by getting a connection to Location Services. If the connection fails,onConnected() isn’t called, and the request stops. The following snippet shows how to start the request:

public class MainActivity extends FragmentActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnAddGeofencesResultListener {
...
/**
* Start a request to remove geofences by calling
* LocationClient.connect()
*/
public void removeGeofences(PendingIntent requestIntent) {
// Record the type of removal request
mRequestType = REMOVE_INTENT;
/*
* Test for Google Play services after setting the request type.
* If Google Play services isn't present, the request can be
* restarted.
*/
if (!servicesConnected()) {
return;
}
// Store the PendingIntent
mGeofenceRequestIntent = requestIntent;
/*
* Create a new location client object. Since the current
* activity class implements ConnectionCallbacks and
* OnConnectionFailedListener, pass the current activity object
* as the listener for both parameters

When Location Services invokes the callback method indicating that the connection is open, make the request to remove all geofences. Disconnect the client after making the request. For example:

public class MainActivity extends FragmentActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnAddGeofencesResultListener {
...
/**
* Once the connection is available, send a request to remove the
* Geofences. The method signature used depends on which type of
* remove request was originally received.
*/
private void onConnected(Bundle dataBundle) {
/*
* Choose what to do based on the request type set in
* removeGeofences
*/
switch (mRequestType) {
...
case REMOVE_INTENT :
mLocationClient.removeGeofences(
mGeofenceRequestIntent, this);
break;
...
}
}
...
}

Although the call to removeGeofences(PendingIntent, LocationClient.OnRemoveGeofencesResultListener) Services calls returns immediately, the result of the removal request is indeterminate until Location Services callsonRemoveGeofencesByPendingIntentResult(). The following snippet shows how to define this method:

public class MainActivity extends FragmentActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnAddGeofencesResultListener {
...
/**
* When the request to remove geofences by PendingIntent returns,
* handle the result.
*
*@param statusCode the code returned by Location Services
*@param requestIntent The Intent used to request the removal.
*/
@Override
public void onRemoveGeofencesByPendingIntentResult(int statusCode,
PendingIntent requestIntent) {
// If removing the geofences was successful
if (statusCode == LocationStatusCodes.SUCCESS) {
/*
* Handle successful removal of geofences here.
* You can send out a broadcast intent or update the UI.
* geofences into the Intent's extended data.
*/
} else {
// If adding the geocodes failed
/*
* Report errors here.
* You can log the error using Log.e() or update
* the UI.
*/
}
/*
* Disconnect the location client regardless of the
* request status, and indicate that a request is no
* longer in progress
*/
mInProgress = false;
mLocationClient.disconnect();
}
...
}

Remove individual geofences

The procedure for removing an individual geofence or set of geofences is similar to the removal of all geofences. To specify the geofences you want remove, add their geofence ID values to a List of String objects. Pass this List to a different definition of removeGeofences with the appropriate signature. This method then starts the removal process.

Start by adding a request type for removing geofences by a list, and also add a global variable for storing the list of geofences:

...
// Enum type for controlling the type of removal requested

Next, define a list of geofences you want to remove. For example, this snippet removes the Geofence defined by the geofence ID “1”:

public class MainActivity extends FragmentActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnAddGeofencesResultListener {
...
List<String> listOfGeofences =
Collections.singletonList("1");
removeGeofences(listOfGeofences);
...
}

The following snippet defines the removeGeofences() method:

public class MainActivity extends FragmentActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnAddGeofencesResultListener {
...
/**
* Start a request to remove monitoring by
* calling LocationClient.connect()
*
*/
public void removeGeofences(List<String> geofenceIds) {
// If Google Play services is unavailable, exit
// Record the type of removal request
mRequestType = REMOVE_LIST;
/*
* Test for Google Play services after setting the request type.
* If Google Play services isn't present, the request can be
* restarted.
*/
if (!servicesConnected()) {
return;
}
// Store the list of geofences to remove
mGeofencesToRemove = geofenceIds;
/*
* Create a new location client object. Since the current
* activity class implements ConnectionCallbacks and
* OnConnectionFailedListener, pass the current activity object
* as the listener for both parameters
*/
mLocationClient = new LocationClient(this, this, this);
// If a request is not already underway
if (!mInProgress) {
// Indicate that a request is underway
mInProgress = true;// Request a connection from the client to Location Services
mLocationClient.connect();
} else {
/*
* A request is already underway. You can handle
* this situation by disconnecting the client,
* re-setting the flag, and then re-trying the
* request.
*/
}
}
...
}

When Location Services invokes the callback method indicating that the connection is open, make the request to remove the list of geofences. Disconnect the client after making the request. For example:

public class MainActivity extends FragmentActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnAddGeofencesResultListener {
...
private void onConnected(Bundle dataBundle) {
...
switch (mRequestType) {
...
// If removeGeofencesById was called
case REMOVE_LIST :
mLocationClient.removeGeofences(
mGeofencesToRemove, this);
break;
...
}
...
}
...
}

Define an implementation of onRemoveGeofencesByRequestIdsResult(). Location Services invokes this callback method to indicate that the request to remove a list of geofences is complete. In this method, examine the incoming status code and take the appropriate action:

public class MainActivity extends FragmentActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnAddGeofencesResultListener {
...
/**
* When the request to remove geofences by IDs returns, handle the
* result.
*
* @param statusCode The code returned by Location Services* @param geofenceRequestIds The IDs removed
*/
@Override
public void onRemoveGeofencesByRequestIdsResult(
int statusCode, String[] geofenceRequestIds) {
// If removing the geocodes was successful
if (LocationStatusCodes.SUCCESS == statusCode) {
/*
* Handle successful removal of geofences here.
* You can send out a broadcast intent or update the UI.
* geofences into the Intent's extended data.
*/
} else {
// If removing the geofences failed
/*
* Report errors here.
* You can log the error using Log.e() or update
* the UI.
*/
}
// Indicate that a request is no longer in progress
mInProgress = false;
// Disconnect the location client
mLocationClient.disconnect();
}
...
}

How to show notification in Android

A notification is a message you can display to the user outside of your application’s normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time.

Notification Display Elements

Notifications in the notification drawer can appear in one of two visual styles, depending on the version and the state of the drawer:

Normal view

The standard view of the notifications in the notification drawer.

Big view

A large view that’s visible when the notification is expanded. Big view is part of the expanded notification feature available as of Android 4.1.

Normal view

A notification in normal view appears in an area that’s up to 64 dp tall. Even if you create a notification with a big view style, it will appear in normal view until it’s expanded. This is an example of a normal view:

How to show notification in Android

The callouts in the illustration refer to the following:

  • 1. Content title
  • 2. Large icon
  • 3. Content text
  • 4. Content info
  • 5. Small icon6. Time that the notification was issued. You can set an explicit value with setWhen(); if you
    don’t it defaults to the time that the system received the notification.
  • Big view

    A notification’s big view appears only when the notification is expanded, which happens
    when the notification is at the top of the notification drawer, or when the user expands the
    notification with a gesture. Expanded notifications are available starting with Android 4.1.
    The following screenshot shows an inbox-style notification:

    How to show notification in Android

    Creating a Notification

    You specify the UI information and actions for a notification in
    a NotificationCompat.Builder object. To create the notification itself, you
    call NotificationCompat.Builder.build(), which returns aNotification object
    containing your specifications. To issue the notification, you pass the Notificationobject to
    the system by calling NotificationManager.notify().

    Creating a simple notification

    The following snippet illustrates a simple notification that specifies an activity to open when the user clicks the notification. Notice that the code creates a TaskStackBuilder object and
    uses it to create thePendingIntent for the action. This pattern is explained in more detail in
    the section Preserving Navigation when Starting an Activity:

    NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, ResultActivity.class);
    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(ResultActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
    stackBuilder.getPendingIntent(
    0,
    PendingIntent.FLAG_UPDATE_CURRENT
    );
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(mId, mBuilder.build());
    
    

    That’s it. Your user has now been notified.

    Applying a big view style to a notification

    To have a notification appear in a big view when it’s expanded, first create
    a NotificationCompat.Builderobject with the normal view options you want. Next,
    call Builder.setStyle() with a big view style object as its argument.

    Remember that expanded notifications are not available on platforms prior to Android 4.1. To
    learn how to handle notifications for Android 4.1 and for earlier platforms, read the section Handling compatibility.

    For example, the following code snippet demonstrates how to alter the notification created in the previous snippet to use the Inbox big view style:

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("Event tracker")
    .setContentText("Events received")
    NotificationCompat.InboxStyle inboxStyle =
    new NotificationCompat.InboxStyle();
    String[] events = new String[6];
    // Sets a title for the Inbox style big view
    inboxStyle.setBigContentTitle("Event tracker details:");
    ...
    // Moves events into the big view
    for (int i=0; i < events.length; i++) {
    inboxStyle.addLine(events[i]);
    }
    // Moves the big view style object into the notification object.
    mBuilder.setStyle(inBoxStyle);
    ...
    // Issue the notification here.
    

Android Membership Module Documentation

Our android membership system is basically based on PARSE. It is the service for providing the backend to the application just like Google App Engine. This module has sign in, sign up ,forget password and logout components.

As far as login is concern it is a two way process i.e. request goes from client to server with unique credentials and corresponding response comes up from server. Here our client side is Android App and server part is served by PARSE.

For setting up the Membership module first we need to sign up for parse and set up the dashboard there.

1. Set up the PARSE Engine Dashboard:

  • First of all go here and complete the sign up process.
  • Android Membership Module Documentation

  • After signing up to PARSE access your dashboard.

Android Membership Module Documentation

If you have not use parse before, then you will see screen like this but with blank main area.
In the top right you can see “Create New App” click on that. And Enter your app name.

Android Membership Module Documentation

After when you will press “Create App” .You can see a window with lot of access key mention on it.

Android Membership Module Documentation

Now copy your “Application ID” and “Client Key” these are important as it will be used in Android App for granting the permissions.

Now that is all for setting up the PARSE.

2. Configure Android App:

  • Import the unzipped module code in to Eclipse.
  • Android Membership Module Documentation

  • Open the BaseActivity.java file under the package org.aynsoft.logInParse and replace the value String Object PARSE_APP_KEY,PARSE_CLIENT_KEY with your API Credentials that you
    have copied earlier.

Now You can embed your functionality with this module….

Here are some screen shots of the app….

Android Membership Module Documentation
Android Membership Module Documentation
Android Membership Module Documentation

Android Sensor Tutorial

Most Android-powered devices have built-in sensors that measure motion, orientation, and various environmental conditions. These sensors are capable of providing raw data with high precision and accuracy, and are useful if you want to monitor three-dimensional device movement or positioning, or you want to monitor changes in the ambient environment near a device. For example, a game might track readings from a device’s gravity sensor to infer complex user gestures and motions, such as tilt, shake, rotation, or swing. Likewise, a weather application might use a device’s temperature sensor and humidity sensor to calculate and report the dewpoint, or a travel application might use the geomagnetic field sensor and accelerometer to report a compass bearing.

The Android platform supports three broad categories of sensors:

  • Motion sensors

    These sensors measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.

  • Environmental sensors

    These sensors measure various environmental parameters, such as ambient air temperature and pressure, illumination, and humidity. This category includes barometers, photometers, and thermometers.

  • Position sensors

    These sensors measure the physical position of a device. This category includes orientation sensors and magnetometers. You can access sensors available on the device and acquire raw sensor data by using the Android sensor framework. The sensor framework provides several classes and interfaces that help you perform a wide variety of sensor-related tasks.

One of the most interesting topics in my opinion is how to
use Sensor in Android. Nowadays our smartphone are full of sensors and we can use it to control somehow our app. The most common sensors are:

  • GPS

  • 1. Proximity sensor
  • 2. Light sensor
  • 3. Temperature sensor
  • 4. Barometer sensor
  • 5. NFC

just to mention some of them. In this post we will explain how to obtain a list of sensor

We can retrieve the sensor list too and we need a bit of code.

Some of the sensors are hardware based and some are software based sensors. Whatever the sensor is , android allows us to get the raw data from these sensors and use it in our application. For this android provides us with some classes.

Android provides SensorManager and Sensor classes to use the sensors in our application. In order to use sensors , first thing you need to do is to instantiate the object of SensorManager class. It can be achieved as follows.

SensorManager sMgr; sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);

The next thing you need to do is to instantiate the object of Sensor class by calling the getDefaultSensor() method of the SensorManager class. Its sytanx is given below

Sensor light; light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);

Once that sensor is declared , you need to register its listener and override two methods which are onAccuracyChanged and onSensorChanged. Its syntax is as follows

 sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL); public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { } 

Getting list of sensors supported.

You can get a list of sensors supported by your device by calling the getSensorList method , which will return a list of sensors containing their name and version number and much more information. You can then iterate the list to get the information. Its syntax is given below:

sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE); List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL); for(Sensor sensor: list){ }

Example

MainActivity.java

package com.example.sensors; import java.util.List; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.Bundle; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { private SensorManager sMgr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView sensorsData = (TextView)findViewById(R.id.textView1); sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE); List list = sMgr.getSensorList(Sensor.TYPE_ALL); StringBuilder data = new StringBuilder(); for(Sensor sensor: list){ data.append(sensor.getName() + "\n"); data.append(sensor.getVendor() + "\n"); data.append(sensor.getVersion() + "\n"); } sensorsData.setText(data); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }

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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ScrollView android:id="@+id/scrollView1" android:layout_width="wrap_content" android:layout_height="wrap_content" 
android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="16dp" android:layout_marginTop="16dp" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> </ScrollView> </RelativeLayout> 

string.xml

< ?xml version="1.0" encoding="utf-8"?> Sensors Settings Hello world! List of sensors supported

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sensors" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.sensors.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

Let’s try to run our Sensor application we just modified. 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

Android Sensor Tutorial

Integrating Google Map

Integrating google maps in your application basically consists of these 4 steps.

  • 1. Download and configure. Google Play Services SDK
  • 2. Create a Hello World Project
  • 3. Obtain API key from google console
  • 4. Specify Android Manifest settings
  • 5. Change your codes for MAP

Step 1

Download and configure Google Play Services SDK

Install Google services SDK

Open your SDK manager in the eclipse by clicking the Window and then selecting the Android SDK manager.

Navigate to the extras tab and select the Google play services and click on install this package. It would be like this.

Integrating Google Map

Import SDK to eclipse

After you download the SDK , click on file tab and select import option. Select existing android application code and press ok. Browse to your android folder and then sdk folder. In sdk folder expand extras folder. Expand google folder and select google play services.

Step 2

Create a hello world project.

Configure your project with SDK

After you import the SDK , you have to add it into your project. For this , right click on your eclipse project and select properties. Select android from left tab and then select add from right below panel and add the project. It would be like this

Integrating Google Map

Step 3

Obtaining the API key

This part is furthur divided into two steps. First you have to get an SHA1 fingerprint key from your pc and then you have to get map API key from google console.

Getting SHA 1 fingerprint key from Eclipse

In eclipse window click on “window” menu then go to “preferences” now click on “android” and finally click on “build” now you can see your project SHA1 fingureprint.

Getting key from Google Console

Open Google Console and sign in by clicking a new project. Click on services from the left tab and then navigate to the Google Maps Android API v2. You have to turn them on like this.

Integrating Google Map

Now again go to the left tab and select API access. And click on create new android key. Now paste the key that you copied and put a semicolon and paste your project name and click create. It would be like this.

Integrating Google Map

Now copy the API key that has been given to your by android , because you have to paste it into your manifest file.

Step 4

Specify Android Manifest settings

The final step is to add the API key to your application. Open your manifest file and place this code right before closing the application tag.

<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="API_KEY"/>

In the second line replace API_KEY with your api key and you are done. You need to add some permissions in your manifest too which are given below in the manifest file.

Step 5

1. Change Manifest

Change the AndroidManifest.xml file to the following code. Add the following permissions to your application.

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.map" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="17" /> <permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" android:protectionLevel="signature" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.map.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> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your_apikey" /> </application> </manifest>

2. Adjust layout file

In this example we use the MapFragment. Change your layout file to the following code

<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" tools:context=".MainActivity" > <fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.MapFragment" /> </RelativeLayout>

3. Cahnge MainActivity

package com.example.map; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class MainActivity extends Activity {
 
 static final LatLng HAMBURG = new LatLng(53.558, 9.927); static final LatLng KIEL = new LatLng(53.551, 9.993); private GoogleMap map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)) .getMap(); Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG) .title("Hamburg")); Marker kiel = map.addMarker(new MarkerOptions() .position(KIEL) .title("Kiel") .snippet("Kiel is cool") .icon(BitmapDescriptorFactory .fromResource(R.drawable.ic_launcher))); // Move the camera instantly to hamburg with a zoom of 15. map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15)); // Zoom in, animating the camera. map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); } @Override
 
 public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }

Integrating Google Map

RTL (Arabic) Language Support in Android

Android 4.1 (Jelly Bean) introduced limited support for bidirectional text in TextView and EditText elements, allowing apps to display and edit text in both left-to-right (LTR) and right-to-left (RTL) scripts. Android 4.2 added full native support for RTL layouts, including layout mirroring, allowing you to deliver the same great app experience to all of your users, whether their language uses a script that reads right-to-left or one that reads left-to-right.

If you do nothing, your app will not change — it will continue to appear as it currently does. However, with a few simple changes, your app will be automatically mirrored when the user switches the system language to a right-to-left script (such as Arabic, Hebrew, or Persian). For example, see the following screenshots of the Settings app:

rtl1
rtl2

To take advantage of RTL layout mirroring, simply make the following changes to your app:

  • 1. Declare in your app manifest that your app supports RTL mirroring.
    Specifically, add android:supportsRtl=”true” to the element in your manifest file.
  • 2. Change all of your app’s “left/right” layout properties to new “start/end” equivalents.
  • – If you are targeting your app to Android 4.2 (the app’s targetSdkVersion or minSdkVersion is 17 or higher), then you should use “start” and “end” instead of “left” and “right”. For example,android:paddingLeft should become android:paddingStart.
  • – If you want your app to work with versions earlier than Android 4.2 (the app’s targetSdkVersion orminSdkVersion is 16 or less), then you should add “start” and end” in addition to “left” and “right”. For example, you’d use both android:paddingLeft and android:paddingStart.

For more precise control over your app UI in both LTR and RTL mode, Android 4.2 includes the following new APIs to help manage View components:

• android:layoutDirection — attribute for setting the direction of a component’s layout.
• android:textDirection — attribute for setting the direction of a component’s text.
• android:textAlignment — attribute for setting the alignment of a component’s text.
• getLayoutDirectionFromLocale() — method for getting the Locale-specified direction

You can even create custom versions of layout, drawables, and other resources for display when a right-to-left script is in use. Simply use the resource qualifier “ldrtl” to tag your resources, meaning “layout direction right-to-left”. To debug and optimize custom right-to-left layouts, HierarchyViewer now lets you see start/end properties, layout direction, text direction, and text alignment for all the Views in the hierarchy.

Over the years we have developed several Arabic Apps, Android and iPhone components, code modules and RTL Frameworks that can work as plug and play solutions for developing new apps.

RTL (Arabic) Language Support in Android
RTL (Arabic) Language Support in Android
RTL (Arabic) Language Support in Android

Contact us to discuss your Arabic mobile application development project.

ANDROID UI

The basic building block for user interface is a View object which is created from the View class and occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components like buttons, text fields, etc.

The ViewGroup is a subclass of View and provides invisible container that hold other Views or other ViewGroups and define their layout properties.

The user interface for each component of your app is defined using a hierarchy of View and ViewGroup objects, as shown in figure 1. Each view group is an invisible container that organizes child views, while the child views may be input controls or other widgets that draw some part of the UI. This hierarchy tree can be as simple or complex as you need it to be (but simplicity is best for performance).

ANDROID UI

To declare your layout, you can instantiate View objects in code and start building a tree, but the easiest and most effective way to define your layout is with an XML file. XML offers a human-readable structure for the layout, similar to HTML.

The name of an XML element for a view is respective to the Android class it represents. So a element creates a TextView widget in your UI, and a element creates a LinearLayout view group.

Android Layout Types

1. Linear Layout

LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally.

•Linear vertically Layout

  &lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot; &gt;  
&lt;/LinearLayout&gt;

• Linear vertically Layout

&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot; 
    android:orientation=&quot;horizontal&quot;&gt;
&lt;/LinearLayout

2. Relative Layout

RelativeLayout is a view group that displays child views in relative positions.

&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot; &gt;
&lt;/RelativeLayout&gt;

3. Table Layout

TableLayout is a view that groups views into rows and columns.

&lt;TableLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot; &gt;

&lt;/TableLayout&gt;

4. Frame Layout

The FrameLayout is a placeholder on screen that you can use to display a single view.

&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot; &gt;

&lt;/FrameLayout&gt;

5. List View

ListView is a view group that displays a list of scrollable items.

&lt;ListView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:id=&quot;@+id/listView1&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot; &gt;

&lt;/ListView&gt;

6. Grid View

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

&lt;GridLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot; &gt;

&lt;/GridLayout&gt;

Layout Attributes

Each layout has a set of attributes which define the visual properties of that layout. There are few common attributes among all the layouts and their are other attributes which are specific to that layout. Following are common attributes and will be applied to all the layouts:

Attribute Description
android:id This is the ID which uniquely identifies the view.
android:layout_width This is the width of the layout.
android:layout_height This is the height of the layout
android:layout_marginTop This is the extra space on the top side of the layout.
android:layout_marginBottom This is the extra space on the bottom side of the layout.
android:layout_marginLeft This is the extra space on the left side of the layout.
android:layout_marginRight This is the extra space on the right side of the layout.
android:layout_gravity This specifies how child Views are positioned.
android:layout_weight This specifies how much of the extra space in the layout should be allocated to the View.
android:layout_x This specifies the x-coordinate of the layout.
android:layout_y This specifies the y-coordinate of the layout.
android:layout_width This is the width of the layout.
android:layout_width This is the width of the layout.
android:paddingLeft This is the left padding filled for the layout.
android:paddingRight This is the right padding filled for the layout.
android:paddingTop This is the top padding filled for the layout.
android:paddingBottom This is the bottom padding filled for the layout.

Here width and height are the dimension of the layout/view which can be specified in terms of dp (Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an inch), px( Pixels), mm ( Millimeters) and finally in (inches).

You can specify width and height with exact measurements but more often, you will use one of these constants to set the width or height:

android:layout_width=wrap_content tells your view to size itself to the dimensions required by its content.

android:layout_width=fill_parent tells your view to become as big as its parent view.
Gravity attribute plays important role in positioning the view object and it can take one or more (separated by ‘|’) of the following constant.

Constant Description
top Push object to the top of its container, not changing its size.
bottom Push object to the bottom of its container, not changing its size.
left Push object to the left of its container, not changing its size.
right Push object to the right of its container, not changing its size.
center_vertical Place object in the vertical center of its container, not changing its size.
fill_vertical Grow the vertical size of the object if needed so it completely fills its container.
center_horizontal Place object in the horizontal center of its container, not changing its size.
fill_horizontal Grow the horizontal size of the object if needed so it completely fills its container.
center Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
fill Grow the horizontal and vertical size of the object if needed so it completely fills its container.
clip_vertical Additional option that can be set to have the top and/or bottom edges of the child clipped to its container’s bounds. The clip will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will clip the top edge, and neither will clip both edges.
clip_horizontal Additional option that can be set to have the left and/or right edges of the child clipped to its container’s bounds. The clip will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the left edge, and neither will clip both edges.
start Push object to the beginning of its container, not changing its size.
end Push object to the end of its container, not changing its size.

Android UI Controls

There are number of UI controls provided by Android that allow you to build the graphical user interface for your app.

S.N. UI Control & Description
1 TextView
This control is used to display text to the user.
2 EditText
EditText is a predefined subclass of TextView that includes rich editing capabilities.
3 AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion suggestions automatically while the user is typing.
4 Button
A push-button that can be pressed, or clicked, by the user to perform an action.
5 ImageButton
AbsoluteLayout enables you to specify the exact location of its children.
6 CheckBox
An on/off switch that can be toggled by the user. You should use checkboxes when presenting users with a group of selectable options that are not mutually exclusive.
7 ToggleButton
An on/off button with a light indicator.
8 RadioButton
The RadioButton has two states: either checked or unchecked.
9 RadioGroup
A RadioGroup is used to group together one or more RadioButtons.
10 ProgressBar
The ProgressBar view provides visual feedback about some ongoing tasks, such as when you are performing a task in the background.
11 Spinner
A drop-down list that allows users to select one value from a set.
12 TimePicker
The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode.
13 DatePicker
The DatePicker view enables users to select a date of the day.

A View is an object that draws something on the screen that the user can interact with and a ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the layout of the user interface.

You define your layout in an XML file which offers a human-readable structure for the layout, similar to HTML. For example, a simple vertical layout with a text view and a button looks like this:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
   android:layout_width=&quot;fill_parent&quot; 
   android:layout_height=&quot;fill_parent&quot;
   android:orientation=&quot;vertical&quot; &gt;
   
   &lt;TextView android:id=&quot;@+id/text&quot;
      android:layout_width=&quot;wrap_content&quot;
      android:layout_height=&quot;wrap_content&quot;
      android:text=&quot;I am a TextView&quot; /&gt;
   &lt;Button android:id=&quot;@+id/button&quot;
      android:layout_width=&quot;wrap_content&quot;
      android:layout_height=&quot;wrap_content&quot;
      android:text=&quot;I am a Button&quot; /&gt;
&lt;/LinearLayout&gt;

Creating a Simple Custom Component

The simplest way to create your custom component is to extend an existing widget class or subclass with your own class if you want to extend the functionality of existing widget like Button, TextView, EditText, ListView, CheckBox etc. otherwise you can do everything yourself by starting with the android.view.View class.

At its simplest form you will have to write your constructors corresponding to all the constructors of the base class. For example if you are going to extend TextView to create a DateView then following three constructors will be created for DateView class:

public class DateView extends TextView {
   public DateView(Context context) {
      super(context);
      //--- Additional custom code --
   }

   public DateView(Context context, AttributeSet attrs) {
      super(context, attrs);
      //--- Additional custom code --
   }

   public DateView(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
      //--- Additional custom code --
   }
}

Because you have created DateView as child of TextView so it will have access on all the attributes, methods and events related to TextView and you will be able to use them without any further implementation. You will implement additional custom functionality inside your own code as explained in the given examples below.

If you have requirement for implementing custom drawing/sizing for your custom widgets then you need to override onMeasure(int widthMeasureSpec, int heightMeasureSpec) and onDraw(Canvas canvas) methods. If you are not going to resize or change the shape of your built-in component then you do not need either of these methods in your custom component.

The onMeasure() method coordinate with the layout manager to report the widget’s width and height, and you need to call setMeasuredDimension(int width, int height) from inside this method to report the dimensions.

You can then execute your custom drawing inside the onDraw(Canvas canvas) method, where android.graphis.Canvas is pretty similar to its counterpart in Swing, and has methods such as drawRect(), drawLine(), drawString(), drawBitmap() etc. which you can use to draw your component.

Android Life Cycle of Activity

Android Life Cycle of Activity

There are 7 life cycle methods of android.app.Activity class. They are as follows:

Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re-enters the activity. For example, if you’re building a streaming video player, you might pause the video and terminate the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to resume the video from the same spot.

This class explains important lifecycle callback methods that each Activity instance receives and how you can use them so your activity does what the user expects and does not consume system resources when your activity doesn’t need them.

Starting an Activity

Unlike other programming paradigms in which apps are launched with a main() method, the Android system initiates code in an Activity instance by invoking specific callback methods that correspond to specific stages of its life cycle.

Resumed

In this state, the activity is in the foreground and the user can interact with it. (Also sometimes referred to as the “running” state.)

Paused

In this state, the activity is partially obscured by another activity—the other activity that’s in the foreground is semi-transparent or doesn’t cover the entire screen. The paused activity does not receive user input and cannot execute any code.

Stopped

In this state, the activity is completely hidden and not visible to the user; it is considered to be in the background. While stopped, the activity instance and all its state information such as member variables is retained, but it cannot execute any code.

Destroy the Activity

While the activity’s first lifecycle callback is onCreate(), its very last callback is onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory.

Most apps don’t need to implement this method because local class references are destroyed with the activity and your activity should perform most cleanup during onPause() and onStop(). However, if your activity includes background threads that you created during onCreate() or other long-running resources that could potentially leak memory if not properly closed, you should kill them during onDestroy().

@Override
public void onDestroy() {
    super.onDestroy();  // Always call the superclass
    
    // Stop method tracing that the activity started during onCreate()
    android.os.Debug.stopMethodTracing();
}

Pausing and Resuming an Activity

During normal app use, the foreground activity is sometimes obstructed by other visual components that cause the activity to pause. For example, when a semi-transparent activity opens (such as one in the style of a dialog), the previous activity pauses. As long as the activity is still partially visible but currently not the activity in focus, it remains paused.

However, once the activity is fully-obstructed and not visible, it stops (which is discussed in the next lesson).

As your activity enters the paused state, the system calls the onPause() method on your Activity, which allows you to stop ongoing actions that should not continue while paused (such as a video) or persist any information that should be permanently saved in case the user continues to leave your app. If the user returns to your activity from the paused state, the system resumes it and calls the onResume() method.

Stopping and Restarting an Activity

Properly stopping and restarting your activity is an important process in the activity lifecycle that ensures your users perceive that your app is always alive and doesn’t lose their progress. There are a few of key scenarios in which your activity is stopped and restarted:

  • • The user opens the Recent Apps window and switches from your app to another app. The activity in your app that’s currently in the foreground is stopped. If the user returns to your app from the Home screen launcher icon or the Recent Apps window, the activity restarts.
  • • The user performs an action in your app that starts a new activity. The current activity is stopped when the second activity is created. If the user then presses the Back button, the first activity is restarted.
  • • The user receives a phone call while using your app on his or her phone.

The Activity class provides two lifecycle methods, onStop() and onRestart(), which allow you to specifically handle how your activity handles being stopped and restarted. Unlike the paused state, which identifies a partial UI obstruction, the stopped state guarantees that the UI is no longer visible and the user’s focus is in a separate activity (or an entirely separate app).

Recreating an Activity

There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling finish(). The system may also destroy your activity if it’s currently stopped and hasn’t been used in a long time or the foreground activity requires more resources so the system must shut down background processes to recover memory.

When your activity is destroyed because the user presses Back or the activity finishes itself, the system’s concept of that Activity instance is gone forever because the behavior indicates the activity is no longer needed. However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the “instance state” and is a collection of key-value pairs stored in a Bundle object.

Creating A Simple Hello World Android Project

Let us start actual programming with Android Framework. Before you start writing your first example using Android SDK, you have to make sure that you have setup your Android development environment properly as explained in Android – Environment Setup tutorial. I also assume that you have a little bit working knowledge with Eclipse IDE.

So let us proceed to write a simple Android Application which will print “Hello World!”.

Create Android Application

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:

Creating A Simple Hello World Android Project

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:

Creating A Simple Hello World Android Project

Anatomy of Android Application

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

Creating A Simple Hello World Android Project

Folder, File & Description

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.

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.

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.

res/drawable-hdpi

This is a directory for drawable objects that are designed for high-density screens.
res/layout:- This is a directory for files that define your app’s user interface.

res/values

This is a directory for other various XML files that contain a collection of resources, such as strings and colors definitions.

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 {

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

elements for activities
elements for services
elements for broadcast receivers
elements for content providers

The Strings File

The 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: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 file, 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 window:

Creating A Simple Hello World Android Project

Congratulations!!! you have developed your first Android Application and now just keep following rest of the tutorial step by step to become a great Android Developer. All the very best.

Setup Android Development Environment- Complete Tutorial

Here starts our Android Development tutorial. In this article, you will find how to setup a complete Android Development environment. This includes download, installation and configuration of various software components required to form a complete IDE. As I said in the Introduction, I’ve tried to keep things as simple as I could. And all you’re supposed to do is to follow some simple steps only. That’s it, not any big deal (Android Development itself is not a big deal and here it is made even more simpler).

This tutorial is based on Windows platform as I’m currently developing on Windows. The setup procedure for Linux and Mac platforms don’t make much difference and all tools required are available for that platforms also. Two things you are required to have is a computer and an internet connection- preferably a high speed one. This is because all those components you are going to download will together consist of several hundreds of megabytes. If you have a low speed dial-up data connection, it will take much time to complete.

These are the components you require to setup your Android IDE:

  • 1. Java Development Kit
  • 2. Android SDK
  • 3. Eclipse

Now its time to download these one by one:

1. JDK(Java Development Kit)

It is the most important one as it forms the base for all other tools. It consists of Java Run time Environment and developer tools. For everything we are going to do here, JDK is required. To download Java SE JDK go to the Java SE download page of Oracle here:

Setup Android Development Environment

Accept the Licence agreement and select the platform

2. Android SDK

Android SDK is the collection of various tools and libraries which is designed to be linked with the development software we are using and make the development environment Android-specific. In our case it is to be linked with the Eclipse (Eclipse is not the only development environment for Android. We use it here ‘cause it is the most popular and simple to work with). Download the latest Android SDK from Android Developers website You can download either the executable installation file or the compressed archive. Both are same.

http://developer.android.com/sdk/index.html

Setup Android Development Environment

3. Eclipse

Eclipse is the highly popular IDE for Java and here we are going to make it an Android specific IDE by installing the ADT plugin and linking with the Android SDK. That is, you are going to do all your coding, testing and debugging works in the Eclipse.
Before downloading the Eclipse, make sure that it is compatible with the Android SDK you’ve just downloaded before.

Currently Eclipse Classic is the recommended version

Download it from here:

http://www.eclipse.org/downloads/

Setup Android Development Environment

Installation:

We’ve completed downloading all the tools essential to start with, now we’ll see how to install these components.

JDK

Installation of the Java SE is a relatively painless task. I think it doesn’t need much explanation. It is an executable installation package and install it like any other software packages. Leave the default packages and installation location unchanged and proceed. After it completes installing JDK, will ask the location for JRE to be installed. No need to change the default location. Click next. After the successful completion of the installation, it will show you a window like this. Click continue.

Android SDK

If you’ve downloaded the zip file of Android SDK, then you need to unzip the archive into the C: drive of your computer such that the software goes into C:/ android-sdk-windows folder (in case of Windows platform). If you downloaded the installation package of Android SDK then install it by setting the installation location to your C:/ root folder.

Eclipse

Eclipse is also zip archive and doesn’t need installation. Just extract the zip file and place it in your C: drive such that the Eclipse software is in C:/Eclipse folder. Then go to that Eclipse folder and find a file namedEclipse.exe. Right click on the file and select Create Shortcut. Copy the shortcut and place it in you desktop.

ADT Plugin for Eclipse

ADT is a custom plugin for Eclipse to give a powerful integrated IDE for Android Development. It allows user to develop, run and debug Android Applications.

Open Eclipse by double clicking the Eclipse shortcut on the desktop. It will ask for the default workspace location. Set it as C:/ Eclipse workspace and continue.
Eclipse window appears. Go to Help->Install New Software.

Setup Android Development Environment

Setup Android Development Environment

  • In the new window click Add
  • Add Repository window opens
  • In the name field enter ‘ADT’
  • In the location field add the URL

https://dl-ssl.google.com/android/eclipse/

Setup Android Development Environment

  • Click OK

If any trouble occurs in downloading, use http in place of https in the URL
In the next window, you will see the list of files to be downloaded. Click Next

Setup Android Development Environment

Next window shows the review of files to be installed. Click Next. Accept the Apache license and continue.

After the installation completes, it will ask you to whether restart the eclipse or not. Click restart Now

Setup Android Development Environment

When Eclipse restarts, configure SDK window appears. Select Use existing SDK option and browse the folder C:/ android-sdk-windows and click Finish.

Setup Android Development Environment

Adding Platform Packages to the Android SDK
We’ve downloaded the Android SDK, but we can’t start development with the Android SDK as it is. This is because it doesn’t contain any packages. We need to add packages to the Android SDK. Packages are specific to a particular version of Android, for example, if we are planning to develop for 2.3, then we want to install the platform packages for Android 2.3 that is API-10. Suppose we want to support the earlier versions of Android and want to test whether our app works without errors in the earlier versions or not. Then we need each of those platforms of the Android versions we are planning to add support to.

Open Android SDK manager. You can open it from its folder or by just clicking the Android SDK manager button on the SDK toolbar.

Setup Android Development Environment

When opens, it will automatically show the packages available for download.

Expand tools on the left. Select SDK tools and SDK platform tools.

Setup Android Development Environment

To select the required packages expand them. Select SDK packages and samples for SDK and GoogleAPI. You need not install the third party SDKs unless you are programming for a particular device. (Google API is also not mandatory, it is required only if we use any Google APIs in our application. For simple applications, it isn’t required) As a beginner, you need to download SDK platform and samples for Android 2.3. Select Google USB driver package under extras, if you want to test your app on a physical device.
After selecting, click Install Packages.

In the next window, the components we’ve selected appears as a list and we can make a review. To reject a package, select it and click Reject.

Setup Android Development Environment

After making the final list of components, click install.

Setup Android Virtual Device
The final step is to configure an Android Virtual Device. Android Virtual Device is the Android emulator on which we are run our program. We can create an AVD to match with the configurations of any Android device available in the market. And there’s no limit in the number of AVDs, we can create as many AVDs as we want in different configurations.

To create an AVD, go to Android Virtual Device Manager button in the Eclipse toolbar. Click New on the Right side.

Setup Android Development Environment

Give any name in the name field. (The name should be such that you can distinguish it later, when multiple AVDs are created). Select the target API from the drop down list. In this case, I’ve selected 2.3 as target. Enter desired size for SD card. Under skin section, leave the default resolution, WVGA800 unchanged.

Setup Android Development Environment

Click create AVD.

The Android Virtual Devise you’ve just created appears on the list of AVDs. Select it and click Start

Setup Android Development Environment

Now your AVD boots. It will take several minutes to load for the first time. After the loading is completed, it shows you an Android Home screen. This is your virtual Android devise where you are going to test- run your programs.

Setup Android Development Environment

Congrats! You’ve completed an important task in your Android development life. You just setup you complete Android Development Environment. You will learn more about the development environment in my upcoming posts.

Introduction to Android

Android is an open Source Operating System for mobile devicessuch as smart phones and tablet computers based on Linux Kernal.Android was developed by the Open Handset Alliance, led by Google, and other companies.

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

Features of Android

  • It is Open Source
  • It provides many Interesting Features like RSS Feeds,Weather Detail,Opening Screen etc.
  • Anyone Can customize the android platform.
  • It provides support for web browser, messaging services, storage, connectivity, media, handset layout etc.
  • Consumer can choose quality Application from vairious play stores etc.

Android Architecture

Android operating system is a stack of software components which is roughly divided into five sections and four main layers as shown below in the architecture diagram.

1

Linux Kernel

In android Architecture layers the Bottom Layer is Linux Kernal.This provides basic system functionality like process management, memory management, device management like camera, keypad, display etc.

Libraries

There is Set of Libraries on the Top of Linux Layer including open-source Web browser engine WebKit, well known library libc, SQLite database.

Android RunTime

This is the third section of the architecture and available on the second layer from the bottom.This section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially designed and optimized for Android.

The Android runtime also provides a set of core libraries which enable Android application developers to write Android applications using standard Java programming language.

Application Framework

The Application Framework layer provides many higher-level services to applications in the form of Java classes. Application developers are allowed to make use of these services in their applications.

Applications

You will find all the Android application at the top layer. You will write your application to be installed on this layer only. Examples of such applications are Contacts Books, Browser, Games etc.

Android Application Components

There are Four Basic Andxroid Application components.They are Activities,Services,Content Provider and roadcast Reciever.

Activity

An activity represents a single screen with a user interface through which user interacts with Application.If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched.

Services

A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.

ContentProvider

A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere else entirely.

BroadcastReciever

Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.

Google Map and Instagram Mashup

This is interesting maspus using the two popular api ie instagram media search and google map.This project uses the map as to set the location and using this location it search the image media recently uploaded on instagram.

1. Creating a google map : You can refer to your previous tutorials for getting start with google map.

2. Creating an Instagram App:

Follow these simple steps to get your own key.

  • 1. Login if your not already.
  • 2. Go to the Instagram Developer page.
  • 3. Click on ”Register your application”.
  • 4. If you don’t already have a application registered, you will now see a form to register a new one. If you instead see a list of ”clients”, click the ”Register new client” at the top right.
  • 5. Set application name to your websites name
  • 6. Type in a description, something like ”Registering to get a client ID
  • 7. Add the url of you site on the two last fields.
  • 8. Hit register.
  • 9. Click ”Manage clients” in the top menu and you will now see you new client in the list and a client id, client secret and more.
  • 10. Save and you are ready to use the Instagram API to search after images directly on Instagram.

Here is the java file to generate the request url for location based media search on Instagram.

package org.aynsoft.javafile;

import android.app.Activity;
import android.util.Log;

import com.google.android.gms.maps.model.LatLng;

public class Utils {
	
	private static final String APIKEY="2f8a844330444c97a6d71cf882e19964";

	private static Utils utils;
	private  Utils() {
		
	}
	
	public static Utils getInstance(){
		if(utils==null){
			utils=new Utils();
			return utils;
		}
		return utils;
	}		
	
	public String getUrlForMediaSearch(LatLng latlng){
		String url="https://api.instagram.com/v1/media/search?" +
				"lat=" +latlng.latitude+
				"&lng=" +latlng.longitude+
				"&client_id="+APIKEY;
		Log.i("Search Url",""+url);
		return url;
	}	
	
	public  void fetchVideoResult(LatLng arg0,Activity activity){
		LoadVideos loader=new LoadVideos(activity);
		loader.execute(Utils.getInstance().getUrlForMediaSearch(
				arg0));
	}
 }

3. A Dive into App: When the app first launch it show the media result on the bases of the current location of the user. An HTTP GET request is generated to get the media from the server.An Instagram generate the json responce of the request.Then wee need to parse that responce using the JSON parser.For holding the data of the media we create a POJO class.

Image.java

package org.aynsoft.javafile;

public class Image {

	
	String mIconUrl;
	String sIconUrl;	
	
	public String getmIconUrl() {
		return mIconUrl;
	}
	public void setmIconUrl(String mIconUrl) {
		this.mIconUrl = mIconUrl;
	}
	public String getsIconUrl() {
		return sIconUrl;
	}
	public void setsIconUrl(String sIconUrl) {
		this.sIconUrl = sIconUrl;
	}
	}
Parser.java
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.util.Log;

public class Parser {
	
	private final  String KEY_DATA="data";
	private final String KEY_IMAGES="images";
	private final String KEY_IMG_LOW="low_resolution";
	private final String KEY_IMG_HIGH="standard_resolution";
	private final String KEY_IMG_URL="url";
	private final String KEY_ID="id";

	public volatile boolean parsingComplete = true;

	
	
	
	@SuppressLint("NewApi")
	public List<Image> getVideoContent(String URL) {
		String in=fetchJSON(URL);
		List<Image> videoList=new ArrayList<Image>();
		try {
			JSONObject reader = new JSONObject(in);					
			JSONArray resultArray=reader.getJSONArray(KEY_DATA);			
			Log.i("Size",""+resultArray.length());
			if(resultArray.length()>0){
				for(int i=0;i<resultArray.length();i++){
					Image video=new Image();
					JSONObject itemObject=resultArray.getJSONObject(i);		
					JSONObject imgObject=itemObject.getJSONObject(KEY_IMAGES);
					video.setmIconUrl(imgObject.getJSONObject(KEY_IMG_LOW).getString(KEY_IMG_URL));
					video.setsIconUrl(imgObject.getJSONObject(KEY_IMG_HIGH).getString(KEY_IMG_URL));
					videoList.add(video);
				}
			}
			parsingComplete = false;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return videoList;

	}
	
	
	public String getLocationID(String URL) {
		String in=fetchJSON(URL);
		String ID=null;
		try {
			JSONObject reader = new JSONObject(in);					
			JSONArray resultArray=reader.getJSONArray(KEY_DATA);				
			if(resultArray.length()>0){
				JSONObject obj=resultArray.getJSONObject(0);
				ID=obj.getString(KEY_ID);
			}
			parsingComplete = false;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ID;

	}

	public String fetchJSON(String URL) {
		try {
			URL url = new URL(URL);			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(10000 /* milliseconds */);
			conn.setConnectTimeout(15000 /* milliseconds */);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			// Starts the query
			conn.connect();
			InputStream stream = conn.getInputStream();
			String data = convertStreamToString(stream);			
			stream.close();
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}
	
	

	static String convertStreamToString(java.io.InputStream is) {
		java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
		return s.hasNext() ? s.next() : "";
	}
}

In this way we got the data from Instagram from the corresponding location.

This is just the code snippet you can download the full source code of the app here.

Android App for Youtube Playlist

This tutorials is about generating an android app for your youtube Playlist.The center line of this tutorials revolves around generating an youtube playlist feed url, pasing xml file by requesting the url and extracting the video related informations.

1. Getting Youtube Playlist Url:

Using the youtube api v2 we can get the url for the playlist feed. You can study the api related documentation here.
Any way this is url format to get the playlist feed for youtube playlist.

http://gdata.youtube.com/feeds/api/playlists/“?v=2&max-results=50

When you retrieve a video feed or list of search results, YouTube returns an Atom feed that contains one tag for each video in the result set. The root XML tag in the response will be the tag. In addition to the information about the individual videos in the result set, the feed will also contain the total number of results in the list, the index of the first item in the list, the number of items in the list and other metadata about the feed.

<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
    xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/'
    xmlns:gml='http://www.opengis.net/gml'
    xmlns:georss='http://www.georss.org/georss'
    xmlns:media='http://search.yahoo.com/mrss/'
    xmlns:batch='http://schemas.google.com/gdata/batch'
    xmlns:yt='http://gdata.youtube.com/schemas/2007'
    xmlns:gd='http://schemas.google.com/g/2005'
    gd:etag='W/&quot;CE4EQH47eCp7ImA9WxRQGEQ.&quot;'>
  <id>tag:youtube.com,2008:standardfeed:global:most_popular</id>
  <updated>2008-07-18T05:00:49.000-07:00</updated>
  <category scheme='http://schemas.google.com/g/2005#kind'
    term='http://gdata.youtube.com/schemas/2007#video'/>
  <title>Most Popular</title>
  <logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo>
  <link rel='alternate' type='text/html'
    href='https://www.youtube.com/browse?s=tr'/>
  <link rel='http://schemas.google.com/g/2005#feed'
    type='application/atom+xml'
    href='https://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2'/>
  <link rel='http://schemas.google.com/g/2005#batch'
    type='application/atom+xml'
    href='https://gdata.youtube.com/feeds/api/standardfeeds/most_popular/batch?v=2'/>
  <link rel='self' type='application/atom+xml'
    href='https://gdata.youtube.com/feeds/api/standardfeeds/most_popular?...'/>
  <link rel='service' type='application/atomsvc+xml'
    href='https://gdata.youtube.com/feeds/api/standardfeeds/most_popular?...'/>
  <link rel='next' type='application/atom+xml'
    href='https://gdata.youtube.com/feeds/api/standardfeeds/most_popular?...'/>
  <author>
    <name>YouTube</name>
    <uri>http://www.youtube.com/</uri>
  </author>
  <generator version='2.0'
    uri='http://gdata.youtube.com/'>YouTube data API</generator>
  <openSearch:totalResults>100</openSearch:totalResults>
  <openSearch:startIndex>1</openSearch:startIndex>
  <openSearch:itemsPerPage>25</openSearch:itemsPerPage>
  <entry gd:etag='W/&quot;C0AMRn47eCp7ImA9WxRQGUw.&quot;'>
    <id>tag:youtube,2008:video:ZTUVgYoeN_b</id>
    <published>2008-07-05T19:56:35.000-07:00</published>
    <updated>2008-07-18T07:21:59.000-07:00</updated>
    <category scheme='http://schemas.google.com/g/2005#kind'
      term='http://gdata.youtube.com/schemas/2007#video'/>
    <category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
      term='Shopping'/>
    <category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
      term='parkas'/>
    <category scheme='http://gdata.youtube.com/schemas/2007/categories.cat'
      term='People' label='People'/>
    <title>Shopping for Coats</title>
    <content type='application/x-shockwave-flash'
      src='http://www.youtube.com/v/ZTUVgYoeN_b?f=gdata_standard...'/>
    <link rel='alternate' type='text/html'
      href='https://www.youtube.com/watch?v=ZTUVgYoeN_b'/>
    <link rel='http://gdata.youtube.com/schemas/2007#video.responses'
      type='application/atom+xml'
      href='https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/responses?v=2'/>
    <link rel='http://gdata.youtube.com/schemas/2007#video.ratings'
      type='application/atom+xml'
      href='https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/ratings?v=2'/>
    <link rel='http://gdata.youtube.com/schemas/2007#video.complaints'
      type='application/atom+xml'
      href='https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/complaints?v=2'/>
    <link rel='http://gdata.youtube.com/schemas/2007#video.related'
      type='application/atom+xml'
      href='https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/related?v=2'/>
    <link rel='http://gdata.youtube.com/schemas/2007#mobile'
      type='text/html' href='https://m.youtube.com/details?v=ZTUVgYoeN_b'/>
    <link rel='http://gdata.youtube.com/schemas/2007#uploader'
      type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/_x5XG1OV2P6uZZ5FSM9Ttw?v=2'/>
    <link rel='self' type='application/atom+xml'
      href='https://gdata.youtube.com/feeds/api/standardfeeds/most_popular/v/ZTUVgYoeN_b?v=2'/>
    <author>
      <name>GoogleDevelopers</name>
      <uri>https://gdata.youtube.com/feeds/api/users/GoogleDevelopers</uri>
      <yt:userId>_x5XG1OV2P6uZZ5FSM9Ttw<</yt:userId>
    </author>
    <yt:accessControl action='comment' permission='allowed'/>
    <yt:accessControl action='commentVote' permission='allowed'/>
    <yt:accessControl action='rate' permission='allowed'/>
    <yt:accessControl action='embed' permission='allowed'/>
    <yt:accessControl action='list' permission='allowed'/>
    <yt:accessControl action='autoPlay' permission='allowed'/>
    <yt:accessControl action='syndicate' permission='allowed'/>
    <gd:comments>
      <gd:feedLink href='https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/comments'
        countHint='9416'/>
    </gd:comments>
    <georss:where>
      <gml:Point>
        <gml:pos>21.37124437061831 -157.87353515625</gml:pos>
      </gml:Point>
    </georss:where>
    <yt:hd/>
    <media:group>
      <media:category label='People'
        scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>People
      </media:category>
      <media:content 
        url='http://www.youtube.com/v/ZTUVgYoeN_b?f=gdata_standard...'
        type='application/x-shockwave-flash' medium='video'
        isDefault='true' expression='full' duration='215' yt:format='5'/>
      <media:content
        url='rtsp://rtsp2.youtube.com/ChoLENy73bIAEQ1kgGDA==/0/0/0/video.3gp'
        type='video/3gpp' medium='video'
        expression='full' duration='215' yt:format='1'/>
      <media:content
        url='rtsp://rtsp2.youtube.com/ChoLENy73bIDRQ1kgGDA==/0/0/0/video.3gp'
        type='video/3gpp' medium='video'
        expression='full' duration='215' yt:format='6'/>
      <media:credit role='uploader' scheme='urn:youtube'
          yt:display='GoogleDevelopers'>GoogleDevelopers</media:credit>
      <media:description type='plain'>
        What could make for more exciting video?
      </media:description>
      <media:keywords>Shopping, parkas</media:keywords>
      <media:license type='text/html' href='http://www.youtube.com/t/terms'>youtube</media:license>
      <media:player url='https://www.youtube.com/watch?v=ZTUVgYoeN_b'/>
      <media:thumbnail url='http://img.youtube.com/vi/ZTUVgYoeN_b/2.jpg'
        height='90' width='120' time='00:00:03.500'/>
      <media:thumbnail url='http://img.youtube.com/vi/ZTUVgYoeN_b/1.jpg'
        height='90' width='120' time='00:00:01.750'/>
      <media:thumbnail url='http://img.youtube.com/vi/ZTUVgYoeN_b/3.jpg'
        height='90' width='120' time='00:00:05.250'/>
      <media:thumbnail url='http://img.youtube.com/vi/ZTUVgYoeN_b/0.jpg'
        height='360' width='480' time='00:00:03.500'/>
      <media:title type='plain'>Shopping for Coats</media:title>
      <yt:aspectRatio>widescreen</yt:aspectRatio>
      <yt:duration seconds='79'/>
      <yt:uploaded>2008-07-05T19:56:35.000-07:00</yt:uploaded>
      <yt:uploaderId>UC_x5XG1OV2P6uZZ5FSM9Ttw</yt:uploaderId>
      <yt:videoid>ZTUVgYoeN_b</yt:videoid>
    </media:group>
    <gd:rating min='1' max='5' numRaters='14763' average='4.93'/>
    <yt:recorded>2008-07-04</yt:recorded>
    <yt:statistics viewCount='383290' favoriteCount='7022'/>
    <yt:rating numDislikes='19257' numLikes='106000'/>
  </entry>
</feed>

2. Jump on to App:

As we have got the url for the playlist feed.Thus to make an app your task would be,

a. Parsing the xml feed: For parsing the xml feed we need to an xml parsing mechanism. Here we use DOM parser. Create a java file name Parser.java

package org.aynsoft.java;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class Parser {
	/** --------------------- Movie Search TAG --------------------- */
	private static final String TAG_GROUP = "media:group";
	private static final String TAG_TITLE = "media:title";
	private static final String TAG_MEDIA_THUMB = "media:thumbnail";
	private static final String TAG_VIDEO_ID = "yt:videoid";
	private static final String TAG_DURATION = "yt:duration";

	/** ---------------------Movie Attribute tags--------------------- */
	private static final String ATR_THUMB_NAME = "yt:name";
	private static final String ATR_THUMB_URL = "url";
	private static final String ATR_DURATION = "seconds";
	/** ---------------------Movie Attribute tags--------------------- */
	private static final String VALUE_ATR_POSTER = "poster";
	private static final String VALUE_ATR_DEFAULT = "default";
	
	

	public NodeList getResponceNodeList(String service_url) {
		String searchResponce = getHttpResponse(URI.create(service_url));
		//Log.i("url",""+service_url);
		Log.i("responce",""+searchResponce);
		Document doc;
		NodeList items = null;
		if (searchResponce != null) {
			Log.i("Not null","executed");
			try {
				doc = this.getDomElement(searchResponce);
				items = doc.getElementsByTagName("entry");				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return items;
	}

	public VideoDetail getResult(NodeList searchresult, int position) {
		VideoDetail result = new VideoDetail();
		try {
			Element e = (Element) searchresult.item(position);
			NodeList list=e.getElementsByTagName(TAG_GROUP);
			Element e1=(Element)list.item(0);
			String title = this.getValue(e1, TAG_TITLE);
			String video_id = this.getValue(e1, TAG_VIDEO_ID);
			String image_url=this.getImageUrlAttributeValue(TAG_MEDIA_THUMB,
					ATR_THUMB_NAME,VALUE_ATR_POSTER, e1);
			if(image_url==null){
				image_url=this.getImageUrlAttributeValue(TAG_MEDIA_THUMB,
						ATR_THUMB_NAME,VALUE_ATR_DEFAULT, e1);
			}
			String duration=this.getAttributeValue(e1, TAG_DURATION, ATR_DURATION);			
			result.setTitle(title);
			result.setVideo_id(video_id);
			result.setDuration(duration);
			result.setIcon_url(image_url);
			
			Log.i("title",""+title);
			Log.i("id",""+video_id);
			Log.i("duration",""+duration);
			Log.i("image_url",""+image_url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public String getImageUrlAttributeValue(String tag,String attribute_key,String attribute_value,Element e){
		NodeList list=e.getElementsByTagName(tag);
		String url=null;
		for(int i=0;i<list .getLength();i++){
			Element element=(Element)list.item(i);
			if(element.getAttribute(attribute_key).equals(attribute_value)){
				url=element.getAttribute(ATR_THUMB_URL);
				return url;
			}
		}
		return url;
	}

	public String getAttributeValue(Element e,String tag,String attribute){
		String atr=null;
		NodeList list=e.getElementsByTagName(tag);
		Element element=(Element)list.item(0);
		atr=element.getAttribute(attribute);		
		return atr;
	}
	
	

	/** In app reused functions */

	private String getUrlContents(String theUrl) {
		
		StringBuilder content = new StringBuilder();
		try {
			URL url = new URL(theUrl);
			URLConnection urlConnection = url.openConnection();
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(urlConnection.getInputStream()), 8);
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				content.append(line + "");
			}
			bufferedReader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content.toString();
		
		
	}
	public static String getHttpResponse(URI uri) {
	    Log.d("Parser", "Going to make a get request");
	    StringBuilder response = new StringBuilder();
	    try {
	        HttpGet get = new HttpGet();
	        get.setURI(uri);
	        DefaultHttpClient httpClient = new DefaultHttpClient();
	        HttpResponse httpResponse = httpClient.execute(get);
	        if (httpResponse.getStatusLine().getStatusCode() == 200) {
	            Log.d("demo", "HTTP Get succeeded");

	            HttpEntity messageEntity = httpResponse.getEntity();
	            InputStream is = messageEntity.getContent();
	            BufferedReader br = new BufferedReader(new InputStreamReader(is));
	            String line;
	            while ((line = br.readLine()) != null) {
	                response.append(line);
	            }
	        }
	    } catch (Exception e) {
	        Log.e("demo", e.getMessage());
	    }
	    Log.d("demo", "Done with HTTP getting");
	    return response.toString();
	}

	public Document getDomElement(String xml) {
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = (Document) db.parse(is);

		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}

		return doc;
	}

	public final String getElementValue(Node elem) {
		Node child;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (child = elem.getFirstChild(); child != null; child = child
						.getNextSibling()) {
					if (child.getNodeType() == Node.TEXT_NODE
							|| (child.getNodeType() == Node.CDATA_SECTION_NODE)) {
						return child.getNodeValue();
					}
				}
			}
		}
		return "";
	}

	public String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return this.getElementValue(n.item(0));
	}

}

b. Retrive the parsing result: First we create a POJO class to hold the data of the videos coming after parsing the xml file.
VideoDetail.java

public class VideoDetail {

	String title;
	String video_id;
	String duration;
	String icon_url;
	
	public String getIcon_url() {
		return icon_url;
	}
	public void setIcon_url(String icon_url) {
		this.icon_url = icon_url;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	
	public String getVideo_id() {
		return video_id;
	}
	public void setVideo_id(String video_id) {
		this.video_id = video_id;
	}
	public String getDuration() {
		return duration;
	}
	public void setDuration(String duration) {
		this.duration = duration;
	}
	
}

Lets us create an activity we will trigger the parsing and displays video data in ListView. This activity contains an AsycTask inner as to start a network operation we need to do it in different thread.

HomeActivity.java

package org.aynsoft.playList;

import java.util.ArrayList;
import java.util.List;

import org.aynsoft.adapter.VideoListAdapter;
import org.aynsoft.java.Parser;
import org.aynsoft.java.VideoDetail;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class HomeActivity extends Activity implements  OnItemClickListener{

	private ListView videoList;
	private VideoListAdapter adapter;
	private List<VideoDetail > list;
	public static final String ID_Extra="ID";
	public static final String PROCESS_DIALOG_MSG="Loading...";
	
	private static final String url="http://gdata.youtube.com/feeds/api/playlists/" +
				"PL4E272D49F6209D23"+//Your playlist ID
				"?v=2&max-results=50";//Number of max counts you want.
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);		
		list=new ArrayList<VideoDetail>();
		adapter=new VideoListAdapter(HomeActivity.this, list);		
		setContentView(R.layout.listview);
		
		
		videoList=(ListView)this.findViewById(R.id.movie_list_view);
		videoList.setAdapter(adapter);
		videoList.setOnItemClickListener(this);		

		//StartLoading
		startLoading(url);
	}	
	
	
	public void startLoading(String url){
		new LoadMoviesAsync().execute(url);
	}
	
	class LoadMoviesAsync extends AsyncTask<String,VideoDetail,Void>{
		ProgressDialog dialog;
		@Override
		protected void onPreExecute() {
			dialog=new ProgressDialog(HomeActivity.this);
			dialog.setMessage(PROCESS_DIALOG_MSG);
			dialog.show();
			super.onPreExecute();
		}		
		@Override
		protected Void doInBackground(String... params) {
			String url=params[0];			
			Parser parser=new Parser();
			NodeList movieContentLst=parser.getResponceNodeList(url);
			//Log.i("HomeActivity",""+movieContentLst.getLength());
			if(movieContentLst!=null){
				for(int i=0;i<movieContentLst.getLength();i++){
					publishProgress(parser.getResult(movieContentLst, i));
				}
			}
			
			return null;
		}
		
		@Override
		protected void onProgressUpdate(VideoDetail... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			addItem(values);
			adapter.notifyDataSetChanged();
		}	
		public void addItem(VideoDetail... items){
			for(VideoDetail item: items){
				list.add(item);
			}	
		}
		@Override
		protected void onPostExecute(Void result) {
			if(dialog.isShowing()){
				dialog.dismiss();
			}		
			Toast.makeText(getBaseContext(), ""+list.size(),Toast.LENGTH_SHORT).show();
			super.onPostExecute(result);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {				
		Intent i=new Intent(HomeActivity.this,YouTubePlayerActivity.class);
		i.putExtra(ID_Extra,""+list.get(arg2).getVideo_id());
		startActivity(i);			
	}
	
}

Above is just the code snippet. You can download the full source code Here.

Google Places API – Tutorial

The Google Places API is a service that returns information about Places — defined within this API as establishments, geographic locations, or prominent points of interest — using HTTP requests. Place requests specify locations as latitude/longitude coordinates.

The following Place requests are available:

  • Place Searches return a list of Places based on a user’s location or search string.
  • Place Details requests return more detailed information about a specific Place, including user reviews.
  • Place Actions allow you to supplement the data in Google’s Places Database with data from your application. You can schedule Events, add and remove Places, or weight Place rankings from user activity with Place Bumps.
  • Place Photos gives you access to the millions of Place related photos stored in Google’s Place database.
  • Place Autocomplete can be used to automatically fill in the name and/or address of a place as you type.
  • Query Autocomplete can be used to provide a query prediction service for text-based geographic searches, by returning suggested queries as you type.
    Each of the services is accessed as an HTTP request, and returns either an JSON or XML response. All requests to a Place service must use the https:// protocol, and include an API key.

Authentication

The Google Places API uses an API key to identify your application. API keys are managed through the Google APIs Console . You’ll need your own server API key before you can begin using the API. To activate the Places API and create your key:

  • Visit the Google APIs Console at https://code.google.com/apis/console and log in with your Google account.
  • A default project called API Project is created for you when you first log in to the APIs Console. You can use the project, or create a new one by clicking the API Project button at the top of the window and selecting Create. Maps API for Business customers must use the API project created for them as part of their Places for Business purchase.
  • Click the Services link in the left-hand navigation panel.
  • Click the status switch (the on/off button) next to the Places API entry. The switch slides to ON.
  • Click API Access in the left-hand navigation panel.
  • Click Create new key for Android App.

Google Places API

Over the years we have developed several Google Map, mashups Android and iPhone components, code modules and Frameworks that can work as plug and play solutions for developing new apps that will substantially reduce the app development cost and time.

Contact us to discuss your multimedia mobile application development project.

Google Places API

Let us take the example to find out the near by places.

To search for specific types of places (such as cafes), you can include the types parameter in your Places Search requests.

https://maps.googleapis.com/maps/api/place/search/json
  ?types=cafe
  &location=37.787930,-122.4074990
  &radius=5000
  &sensor=false
  &key=YOUR_API_KEY

2. Try specifying multiple place types by modifying the URL below to include other place types separated by a pipe ( | ) character in the URL. The Places Search API will return Places associated with any of the types that you specify. The example below demonstrates how to search for places that are considered a cafe or a bakery or both:

https://maps.googleapis.com/maps/api/place/search/json
  ?types=cafe|bakery
  &location=37.787930,-122.4074990
  &radius=5000
  &sensor=false
  &key=YOUR_API_KEY

3. To retrieve places based by distance:

  • 1. Remove the radius parameter from your Place Search request.
  • 2. Add a rankby=distance parameter/value pair.
  • 3. Include one or more of the keyword, name, or types parameters.

For example, the URL below can be used to specify a search for cafes near downtown San Francisco, with results ordered by distance from the location:

https://maps.googleapis.com/maps/api/place/search/json
  ?types=cafe
  &rankby=distance
  &location=37.787930,-122.4074990
  &sensor=false
  &key=YOUR_API_KEY

Place.java :

public class Place {
    private String id;
    private String icon;
    private String name;
    private String vicinity;
    private Double latitude;
    private Double longitude;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getIcon() {
        return icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }
    public Double getLatitude() {
        return latitude;
    }
    public void setLatitude(Double latitude) {
        this.latitude = latitude;
    }
    public Double getLongitude() {
        return longitude;
    }
    public void setLongitude(Double longitude) {
        this.longitude = longitude;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getVicinity() {
        return vicinity;
    }
    public void setVicinity(String vicinity) {
        this.vicinity = vicinity;
    }

    static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
        try {
            Place result = new Place();
            JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
            JSONObject location = (JSONObject) geometry.get("location");
            result.setLatitude((Double) location.get("lat"));
            result.setLongitude((Double) location.get("lng"));
            result.setIcon(pontoReferencia.getString("icon"));
            result.setName(pontoReferencia.getString("name"));
            result.setVicinity(pontoReferencia.getString("vicinity"));
            result.setId(pontoReferencia.getString("id"));
            return result;
        } catch (JSONException ex) {
            Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public String toString() {
        return "Place{" + "id=" + id + ", icon=" + icon + ", name=" + name + ", latitude=" + latitude + ", longitude=" + longitude + '}';
    }

}

PlacesService.java:

public class PlacesService {

 private String API_KEY;

 public PlacesService(String apikey) {
  this.API_KEY = apikey;
 }

 public void setApiKey(String apikey) {
  this.API_KEY = apikey;
 }

 public ArrayList<place> findPlaces(double latitude, double longitude,
   String placeSpacification) {

  String urlString = makeUrl(latitude, longitude, placeSpacification);

  try {
   String json = getJSON(urlString);

   System.out.println(json);
   JSONObject object = new JSONObject(json);
   JSONArray array = object.getJSONArray("results");

   ArrayList<place> arrayList = new ArrayList<place>();
   for (int i = 0; i < array.length(); i++) {
    try {
     Place place = Place
       .jsonToPontoReferencia((JSONObject) array.get(i));
     Log.v("Places Services ", "" + place);
     arrayList.add(place);
    } catch (Exception e) {
    }
   }
   return arrayList;
  } catch (JSONException ex) {
   Logger.getLogger(PlacesService.class.getName()).log(Level.SEVERE,
     null, ex);
  }
  return null;
 }

 // https://maps.googleapis.com/maps/api/place/search/json?location=28.632808,77.218276&radius=500&types=atm&sensor=false&key=apikey
 private String makeUrl(double latitude, double longitude, String place) {
  StringBuilder urlString = new StringBuilder(
    "https://maps.googleapis.com/maps/api/place/search/json?");

  if (place.equals("")) {
   urlString.append("&location=");
   urlString.append(Double.toString(latitude));
   urlString.append(",");
   urlString.append(Double.toString(longitude));
   urlString.append("&radius=1000");
   // urlString.append("&types="+place);
   urlString.append("&sensor=false&key=" + API_KEY);
  } else {
   urlString.append("&location=");
   urlString.append(Double.toString(latitude));
   urlString.append(",");
   urlString.append(Double.toString(longitude));
   urlString.append("&radius=1000");
   urlString.append("&types=" + place);
   urlString.append("&sensor=false&key=" + API_KEY);
  }
  return urlString.toString();
 }

 protected String getJSON(String url) {
  return getUrlContents(url);
 }

 private String getUrlContents(String theUrl) {
  StringBuilder content = new StringBuilder();
  try {
   URL url = new URL(theUrl);
   URLConnection urlConnection = url.openConnection();
   BufferedReader bufferedReader = new BufferedReader(
     new InputStreamReader(urlConnection.getInputStream()), 8);
   String line;
   while ((line = bufferedReader.readLine()) != null) {
    content.append(line + "\n");
   }
   bufferedReader.close();
  }catch (Exception e) {
   e.printStackTrace();
  }
  return content.toString();
 }
}
</place></place></place>

MainActivity.java:

public class MainActivity extends Activity {

 private final String TAG = getClass().getSimpleName();
 private GoogleMap mMap;
 private String[] places;
 private LocationManager locationManager;
 private Location loc;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  initCompo();
  places = getResources().getStringArray(R.array.places);
  currentLocation();
  final ActionBar actionBar = getActionBar();
  actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
  actionBar.setListNavigationCallbacks(ArrayAdapter.createFromResource(
    this, R.array.places, android.R.layout.simple_list_item_1),
    new ActionBar.OnNavigationListener() {
     @Override
     public boolean onNavigationItemSelected(int itemPosition,
       long itemId) {
      if (loc != null) {
       mMap.clear();
       new GetPlaces(MainActivity.this,
         places[itemPosition].toLowerCase().replace(
           "-", "_")).execute();
      }
      return true;
     }
    });
 }

 private class GetPlaces extends AsyncTask<void arraylist="" lace="" void="">> {

  private ProgressDialog dialog;
  private Context context;
  private String places;

  public GetPlaces(Context context, String places) {
   this.context = context;
   this.places = places;
  }

  @Override
  protected void onPostExecute(ArrayList<place> result) {
   super.onPostExecute(result);
   if (dialog.isShowing()) {
    dialog.dismiss();
   }
   for (int i = 0; i < result.size(); i++) {
    mMap.addMarker(new MarkerOptions()
      .title(result.get(i).getName())
      .position(
        new LatLng(result.get(i).getLatitude(), result
          .get(i).getLongitude()))
      .icon(BitmapDescriptorFactory
        .fromResource(R.drawable.pin))
      .snippet(result.get(i).getVicinity()));
   }
                        CameraPosition cameraPosition = new CameraPosition.Builder()
     .target(new LatLng(result.get(0).getLatitude(), result
       .get(0).getLongitude())) // Sets the center of the map to
           // Mountain View
     .zoom(14) // Sets the zoom
     .tilt(30) // Sets the tilt of the camera to 30 degrees
     .build(); // Creates a CameraPosition from the builder
   mMap.animateCamera(CameraUpdateFactory
     .newCameraPosition(cameraPosition));
  }

  @Override
  protected void onPreExecute() {
   super.onPreExecute();
   dialog = new ProgressDialog(context);
   dialog.setCancelable(false);
   dialog.setMessage("Loading..");
   dialog.isIndeterminate();
   dialog.show();
  }

  @Override
  protected ArrayList<place> doInBackground(Void... arg0) {
   PlacesService service = new PlacesService(
     "Put your project browser API key here");
   ArrayList<place> findPlaces = service.findPlaces(loc.getLatitude(), // 28.632808
     loc.getLongitude(), places); // 77.218276


   for (int i = 0; i < findPlaces.size(); i++) {

    Place placeDetail = findPlaces.get(i);
    Log.e(TAG, "places : " + placeDetail.getName());
   }
   return findPlaces;
  }
 }

 private void initCompo() {
  mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
    .getMap();
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 private void currentLocation() {
  locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

  String provider = locationManager
    .getBestProvider(new Criteria(), false);

  Location location = locationManager.getLastKnownLocation(provider);

  if (location == null) {
   locationManager.requestLocationUpdates(provider, 0, 0, listener);
  } else {
   loc = location;
   new GetPlaces(MainActivity.this,
     places[0].toLowerCase().replace(
       "-", "_")).execute();
   Log.e(TAG, "location : " + location);
  }

 }

 private LocationListener listener = new LocationListener() {

  @Override
  public void onStatusChanged(String provider, int status, Bundle extras) {
  }

  @Override
  public void onProviderEnabled(String provider) {
  }

  @Override
  public void onProviderDisabled(String provider) {
  }

  @Override
  public void onLocationChanged(Location location) {
   Log.e(TAG, "location update : " + location);
   loc = location;
   locationManager.removeUpdates(listener);
  }
 };
}

+++++++++++++++++++

We have considerable experience in developing apps using Google Places API.
Photos – City Guide

Over the years we have developed several advanced Google Places and Google Map based Android and iPhone components, code modules and Frameworks that can work as plug and play solutions for developing new apps that will substantially reduce the app development cost and time.

Contact us to discuss your Google Places or Map based mobile application development project.

Amazon Product Advertising API Tutorial

Before using the Product Advertising API, you need to get register and become an author.

To become a Product Advertising API developer, sign up or login.

After Login/Sign Up following will come out.

You need security credentials to call the Product Advertising API, authenticate requests, and identify yourself as the sender of a request. Two types of credentials are available:

AWS security credentials (access key ID and secret access key)

X.509 certificates

Amazon Product Advertising API Tutorial

After creating your security credentials ,you need to download it, and maintain the record of ACCESS_KEY,SECRAT_KEY as it will be needed to make request to the amazon for searching products.

Product Advertising API Operations

a. Find Items

Use the following Product Advertising API operations to return a list of items that satisfy your search criteria.

ItemSearch Find items that are sold on www.amazon.com by merchants and most sellers.
SimilarityLookup Find items that are similar to ones you’ve already found.

b.Find Out More About Specific Items

Once you use the Product Advertising API operations in the previous section to get a list of items that match your search criteria, you can use the following Product Advertising API operations to return additional information about specific items.

ItemLookup Returns descriptions of specified items.

Building up REST Request

a.Required Parameters

The parameters in the following table are required in every request.

Parameter

Value

Description

Service AWSECommerceService Specifies the Product Advertising API service
AWSAccessKeyId Your Amazon-assigned Access Key ID To register for an Access Key ID from the Amazon Web site, go tohttp://aws.amazon.com. Every Product Advertising API 4.0 request must contain either an Access Key ID or a Subscription ID but not both.
SubscriptionId Your Amazon-assigned subscription ID Every Product Advertising API 4.0 request must contain either an Access Key ID or a Subscription ID but not both. Starting with version 2005-10-05, Product Advertising API stopped distributing Subscription IDs. If you already have one, it will continue to work.
AssociateTag An Amazon-assigned Associate ID The AssociateTag enables product URLs returned by Product Advertising API to be tagged as originating from your Associates website. For your requesst to work and to receive a referral credit for a sale, you must include an AssociateTag value in all your requests. Be sure to specify the value correctly; no error is generated for incorrect values.
Operation Operation you wish to perform, for example,ItemLookup One of the Product Advertising API operation types.

b.General and Optional Parameters.

Parameter

Value

Description

MerchantId

An optional parameter that can be used to filter search results and offer listings to include only items sold by Amazon. By default, the API will return items sold by various merchants including Amazon.

The only valid optional value is “Amazon”.

ResponseGroup

Various

Specifies what subset of data to return. The API Reference Guide specifies the response groups that can be used with each operation..

Version

Various

Version of the Product Advertising API 4.0 WSDL. The default is 2011-08-01. If you want another version, including the latest, you must specify it in your request.

c.ItemSearch Request Structure

Below is the GET request structure for the product search api. One has to query this url for the retrieving the desired result.

d.	http://webservices.amazon.com/onca/xml?
e.	Service=AWSECommerceService&
f.	AWSAccessKeyId=[AWS Access Key ID]&
g.	Operation=ItemSearch&
h.	Keywords=Potter&
i.	SearchIndex=Books&
j.	&Timestamp=[YYYY-MM-DDThh:mm:ssZ]
k.	&Signature=[Request Signature]

d. ItemLookUp Request Structure

l.	http://webservices.amazon.com/onca/xml?
m.	Service=AWSECommerceService&
n.	AWSAccessKeyId=[AWS Access Key ID]&
o.	Operation=ItemLookUp&
p.	ItemId=xyz
q.	SearchIndex=Books&
r.	&Timestamp=[YYYY-MM-DDThh:mm:ssZ]
s.	&Signature=[Request Signature]

Building up Sample Project

Here is an sample example for building a amazon mobile app search .For building an sample app that search the mobile app feeded by Amazon Product Advertisement API.

• Create a Android Application Project.

amazon2

• Create a SignedRequestsHelper.java file, this code is for signing the REST request and generating the Signature, which is needed for authentication.

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TimeZone;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class SignedRequestsHelper {
  private static final String UTF8_CHARSET = "UTF-8";
  private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
  private static final String REQUEST_URI = "/onca/xml";
  private static final String REQUEST_METHOD = "GET";

  // use xml-uk.amznxslt.com for xslt requests, or ecs.amazonaws.co.uk for others
  private String endpoint = "webservices.amazon.com"; // must be lowercase
 
  // change this so reads from properties file
  private String awsAccessKeyId = "AKIAJBVTJSNL6UC7CY5A";
  private String awsSecretKey = "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";

  private SecretKeySpec secretKeySpec = null;
  private Mac mac = null;

  public SignedRequestsHelper() throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    byte[] secretyKeyBytes = awsSecretKey.getBytes(UTF8_CHARSET);
    secretKeySpec =
      new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM);
    mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
    mac.init(secretKeySpec);
  }

  public String sign(Map<String, String> params) {
    params.put("AWSAccessKeyId", awsAccessKeyId);
    params.put("Timestamp", timestamp());

    SortedMap<String, String> sortedParamMap =
      new TreeMap<String, String>(params);
    String canonicalQS = canonicalize(sortedParamMap);
    String toSign =
      REQUEST_METHOD + "\n"
      + endpoint + "\n"
      + REQUEST_URI + "\n"
      + canonicalQS;

    String hmac = hmac(toSign);
    String sig = percentEncodeRfc3986(hmac);
    String url = "http://" + endpoint + REQUEST_URI + "?" +
    canonicalQS + "&Signature=" + sig;

    return url;
  }

  private String hmac(String stringToSign) {
    String signature = null;
    byte[] data;
    byte[] rawHmac;
    try {
      data = stringToSign.getBytes(UTF8_CHARSET);
      rawHmac = mac.doFinal(data);
      Base64 encoder = new Base64();
      signature = new String(encoder.encode(rawHmac));
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(UTF8_CHARSET + " is unsupported!", e);
    }
    return signature;
  }

  private String timestamp() {
    String timestamp = null;
    Calendar cal = Calendar.getInstance();
    DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    dfm.setTimeZone(TimeZone.getTimeZone("GMT"));
    timestamp = dfm.format(cal.getTime());
    return timestamp;
  }

  private String canonicalize(SortedMap<String, String> sortedParamMap)
{
    if (sortedParamMap.isEmpty()) {
      return "";
    }

    StringBuffer buffer = new StringBuffer();
    Iterator<Map.Entry<String, String>> iter =
      sortedParamMap.entrySet().iterator();

    while (iter.hasNext()) {
      Map.Entry<String, String> kvpair = iter.next();
      buffer.append(percentEncodeRfc3986(kvpair.getKey()));
      buffer.append("=");
      buffer.append(percentEncodeRfc3986(kvpair.getValue()));
      if (iter.hasNext()) {
        buffer.append("&");
      }
    }
    String cannoical = buffer.toString();
    return cannoical;
  }

  private String percentEncodeRfc3986(String s) {
    String out;
    try {
      out = URLEncoder.encode(s, UTF8_CHARSET)
      .replace("+", "%20")
      .replace("*", "%2A")
      .replace("%7E", "~");
    } catch (UnsupportedEncodingException e) {
      out = s;
    }
    return out;
  }
}

• Create a java file for passing the GET request parameters building the query parameters. UrlParameterHandler.java file is responsible for maintaining the record of the parameters in Map

Where Map key corresponds to parameter key and Map Value corresponds to query parameter valid value.

import java.util.HashMap;
import java.util.Map;

public class UrlParameterHandler {

	public static UrlParameterHandler paramHandler;
	private UrlParameterHandler() {}
	
	
	public static synchronized UrlParameterHandler getInstance(){
		if(paramHandler==null){
			paramHandler=new UrlParameterHandler();
			return paramHandler;
		}
		return paramHandler; 				
	}
	
	public  Map<String,String> buildMapForItemSearch(){
		Map<String, String> myparams = new HashMap<String, String>();
		myparams.put("Service", "AWSECommerceService");
		myparams.put("Operation", "ItemSearch");
		myparams.put("Version", "2009-10-01");
		myparams.put("ContentType", "text/xml");
		myparams.put("SearchIndex", "MobileApps");//for searching mobile apps
		myparams.put("Keywords", "games");
		myparams.put("AssociateTag", "apps");
		myparams.put("MaximumPrice","1000");
		myparams.put("Sort","price");
		myparams.put("ResponseGroup", "Images,Small");
		return myparams;
	}
	
}

• Now we have the request URL builder set ready for the querying the Amazon api. As we are going to make a GET request to the REST API thus we have to build use AsycTask for doing this ,as for calling a network operation we have to use this in background thread.

Here is the code for parsing the responce..

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class Parser {
	/** ---------------------  Search TAG --------------------- */
	private static final String KEY_ROOT="Items";
	private static final String KEY_REQUEST_ROOT="Request";
	private static final String KEY_REQUEST_CONTAINER="IsValid";
	private static final String KEY_ITEM="Item";
	private static final String KEY_ID="ASIN";
	private static final String KEY_ITEM_URL="DetailPageURL";
	private static final String KEY_IMAGE_ROOT="MediumImage";
	private static final String KEY_IMAGE_CONTAINER="URL";
	private static final String KEY_ITEM_ATTR_CONTAINER="ItemAttributes";
	private static final String KEY_ITEM_ATTR_TITLE="Title";		
	
	private static final String VALUE_VALID_RESPONCE="True";
	
	//Tags
	//Items,Request,IsValid,Item,ASIN,DetailPageURL,MediumImage,URL,ItemAttributes,Title


	public NodeList getResponceNodeList(String service_url) {
		String searchResponce = this.getUrlContents(service_url);
		Log.i("url",""+service_url);
		Log.i("responce",""+searchResponce);
		Document doc;
		NodeList items = null;
		if (searchResponce != null) {
			try {
				doc = this.getDomElement(searchResponce);
				items = doc.getElementsByTagName(KEY_ROOT);
				Element element=(Element)items.item(0);
				if(isResponceValid(element)){
					items=doc.getElementsByTagName(KEY_ITEM);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return items;
	}	

	public SearchObject getSearchObject(NodeList list,int position){
		SearchObject object=new SearchObject();
		Element e=(Element)list.item(position);
		object.setUrl(this.getValue(e, KEY_ITEM_URL));
		object.setId(this.getValue(e, KEY_ID));
		object.setImageUrl(this.getValue((Element)(e.getElementsByTagName(KEY_IMAGE_ROOT).item(0))
				, KEY_IMAGE_CONTAINER));
		object.setTitle(this.getValue((Element)(e.getElementsByTagName(KEY_ITEM_ATTR_CONTAINER).item(0))
				, KEY_ITEM_ATTR_TITLE));		
		return object;
	}
	
	public boolean isResponceValid(Element element){		
		NodeList nList=element.getElementsByTagName(KEY_REQUEST_ROOT);
		Element e=(Element)nList.item(0);
		if(getValue(e, KEY_REQUEST_CONTAINER).equals(VALUE_VALID_RESPONCE)){
			return true;
		}
		return false;
	}
	
	/** In app reused functions */

	private String getUrlContents(String theUrl) {
		StringBuilder content = new StringBuilder();
		try {
			URL url = new URL(theUrl);
			URLConnection urlConnection = url.openConnection();
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(urlConnection.getInputStream()), 8);
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				content.append(line + "");
			}
			bufferedReader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content.toString();
	}

	public Document getDomElement(String xml) {
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = (Document) db.parse(is);

		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}

		return doc;
	}

	public final String getElementValue(Node elem) {
		Node child;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (child = elem.getFirstChild(); child != null; child = child
						.getNextSibling()) {
					if (child.getNodeType() == Node.TEXT_NODE
							|| (child.getNodeType() == Node.CDATA_SECTION_NODE)) {
						return child.getNodeValue();
					}
				}
			}
		}
		return "";
	}

	public String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return this.getElementValue(n.item(0));
	}
}

So implement this parser in your application to get the search result.

++++++++++++++++++

We have considerable experience in developing apps using Amazon API.

Over the years we have developed several advanced Amazon based Android and iPhone components, code modules and Frameworks that can work as plug and play solutions for developing new apps that will substantially reduce the app development cost and time.

Contact us

to discuss your Amazon based mobile application development project

Media Player, Audio Player, Video Player Mobile Apps – Tutorial

The main components for developing multimedia mobile applications include:

a. Audio Player:

Audio Player app allows user to listen to the audio/music present in phone with cross feature of remote streaming, internet radio and unlimited song library feeding by youtube.

This app scans all the music present locally in the phone. and present the under TABS like SONGS, render by CUSTOM LISTVIEW of all song with thumbnails, GENRES render by GRIDVIEW with thumbnails, ALBUMS and ARTIST with same mechanism as prior.

Data is retrieved by queering system using CONTENT RESOLVER (This class provides applications access to the content model.) with MediaStore.Audio. (Container for all audio content).

Media is player using MediaPlayer class. MediaPlayer class can be used to control playback of audio/video files and streams.

This app allows remote steaming using same MediaPlayer class, which support both http/rtsp protocols. Several Internet radio stations is already feeded into the app to facilitate the user using the SHOUTCAST apis.

User can search for the song through the unlimited library which is powered by the YOUTUBE and PARSED using the YOUTUBE API.

Also allow to listen to the those video playback in audio player using the RTSP host URL provider by the YOUTUBE.

This application demands the uses permissions like READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, ACCESS_NETWORK_STATE,INTERNET

b. Video Player:

Video Player is an android app to play the video file present in the phone, Using the android VIDEOVIEW with custom implementation of the MEDIACONTROLLER and feature like bookmark video and YOUTUBE video.

Displays a video file. The VideoView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the video so that it can be used in any layout manager, and provides various display options such as scaling and tinting.

MediaController is a view containing controls for a MediaPlayer. Typically contains the buttons like “Play/Pause”, “Rewind”, “Fast Forward” and a progress slider. It takes care of synchronizing the controls with the state of the MediaPlayer.

Video is retrieved by queering system using CONTENT RESOLVER (This class provides applications access to the content model.) with MediaStore.Video.( Container for all Video content).

User can search for the video through the unlimited library which is powered by the YOUTUBE and PARSED using the YOUTUBE API , and bookmark it for the watch later purpose.In the feature of bookmark SQLite Database Table is maintained to store the TITLE, URL and THUMBNAIL IMAGE Path which is cached to meet meet offline render purpose.

This app has the bookmark offline video feature as well which also done by maintaining a SQLite TABLE.

This application demands the uses permissions like READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, ACCESS_NETWORK_STATE,INTERNET

We have considerable experience in developing apps for the entertainment and multimedia industry. That includes custom audio player, audio streaming player, video player, movie trailers, movie apps and usage of API’s from YouTube and DailyMotion.com

Photos – Trailer, Audio Player, Streaming Audio Player, Video Player, Audio Player, Ringtone

Over the years we have developed several advanced multimedia Android and iPhone components, code modules and Frameworks that can work as plug and play solutions for developing new apps that will substantially reduce the app development cost and time.

Contact us to discuss your multimedia mobile application development project.

Photo Gallery, Camera, Recording Apps – Tutorial

The main components for developing Camera and Photo related mobile applications include:

a. Photo Gallery

Photo Gallery app facilitate user to view photos stored in his/her device and perform certain action using them like set as wallpaper, share, edit etc

This app scan all the photo stored in the phone by querying the system for the MEDIASTORE.IMAGES (Contains meta data for all available images) through CONTENT RESOLVER (This class provides applications access to the content model.). After getting the result app extracts the media URI, and parent directory.

In such a way categories the Images corresponding to the parent directory. App shows the parent list in the right pane with one consisting Image as INDIACATOR using the CUSTOM LISTVIEW.Once Click on the LISTVIEW right pane GRID VIEW . Right pane GRID VIEW updated corresponding to the LEFT PANE ITEMCLICKED.

VIEW PAGER is used to render the full screen view of the image which in turn uses IMAGE SCALING according to the DEVICE WIDTH/RESOLUTION. It has the Image sharing option using the SHARE INTENT. SET As WALLPAPER using the WALLPAPER MANAGER (Provides access to the system wallpaper).

This application demands the uses permissions like READ_EXTERNAL_STORAGE, SET_WALLPAPER, WRITE_EXTERNAL_STORAGE.

b. Camera App:

Camera app is a replacement for default camera app client or camera module for a build up project.

It render the SURFACE VIEW with the CAMERA.SURFACE VIEW Provides a dedicated drawing surface embedded inside of a view hierarchy and The Camera class is used to set image capture settings, start/stop preview, snap pictures, and retrieve frames for encoding for video. This class is a client for the Camera service, which manages the actual camera hardware.

It capture frame on BUTTON Click and save it in phone using OUTPUTSTREAM. It has the Image sharing option using the SHARE INTENT. SET As WALLPAPER using the WALLPAPER MANAGER (Provides access to the system wallpaper).

+++++++++++

We have considerable experience in developing apps for photo and camera modules. That includes custom camera app, video recorder, wallpaper, photo gallery, Selfie related apps.

Photos – Camera App, Selfie, Meme, Selfie with MEME, Mirror, Video Recorder, Selfie video, Photo Gallery, Wallpaper, Greeting Card

Over the years we have developed several advanced camera and photo gallery related Android and iPhone components, code modules and Frameworks that can work as plug and play solutions for developing new apps that will substantially reduce the app development cost and time.

Contact us to discuss your photo/camera mobile application development project

Twitter API – Tutorial

To create a twitter app, the first thing you need to do to get your Twitter API key is to create a Twitter application through their site. Visit dev.twitter.com/apps and login to your Twitter account. Then, just fill out the basic information for the application and it’s ready to be published.

Twitter API

Name – This field will be the display name of your application and will be used during user authentication. It will be checked against all other Twitter applications, so make sure to use a unique name.

Description – Write a short description on what you intend to do with the application.

Website – Fill in the full URL (including http://www) of the website you intend to either use the application or make it available for public download.

Callback URL – If you intend to return your users to a specific URL after authentication, specify it here. In basic cases like WordPress widget integration, this field can be left blank.

Read and agree to the Developer Rules of the Road, enter the Captcha phrase, and create! You’re now done creating your application, that wasn’t so hard was it?

Now that you’ve created your application, Twitter has assigned you a few data points to work with.

Twitter API

You must create a personal Access Token and Secret key to allow you to unlock personal account functions with your application – just click ‘Create Access Token’ and Twitter will add these data points as well.

If your application requires additional functionality, you can increase the default Access Level from Read-only to Read-Write or even Read-Write-DirectMessage. If you’re creating an application that only needs to pull tweets, Read-only is all you need.

In basic cases like WordPress widget integration, all you’ll likely need are the Consumer Key & Secret with the Access Token & Secret. These API keys let Twitter know that you’re a registered Twitter user that has a certain level of access to their API, so keep these keys secret.

Now you’re all set to create your Twitter Application in order to get your API Key.

1. Create a Android Project.
Create a Parser Class which facilitates the functionality of the parsing the Twitter Time Line Feed.

Parser.java
package org.aynsoft.java;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import android.util.Base64;
import com.google.gson.Gson;
public class Parser {

	final static String CONSUMER_KEY = "YOUR CONSUMER KEY";
	final static String CONSUMER_SECRET = "YOUR CONSUMER SECRET KEY";
	final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
	final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";

	public Parser() {		
	}
	
	// converts a string of JSON data into a Twitter object
	public Twitter jsonToTwitter(String result) {
		Twitter twits = null;
		if (result != null && result.length() > 0) {
			try {
				Gson gson = new Gson();
				twits = gson.fromJson(result, Twitter.class);
			} catch (IllegalStateException ex) {
				// just eat the exception
			}
		}
		return twits;
	}

	// convert a JSON authentication object into an Authenticated object
	public Authenticated jsonToAuthenticated(String rawAuthorization) {
		Authenticated auth = null;
		if (rawAuthorization != null && rawAuthorization.length() > 0) {
			try {
				Gson gson = new Gson();
				auth = gson.fromJson(rawAuthorization, Authenticated.class);
			} catch (IllegalStateException ex) {
				ex.printStackTrace();
			}
		}
		return auth;
	}

	public String getResponseBody(HttpRequestBase request) {
		StringBuilder sb = new StringBuilder();
		try {

			DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
			HttpResponse response = httpClient.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			String reason = response.getStatusLine().getReasonPhrase();

			if (statusCode == 200) {

				HttpEntity entity = response.getEntity();
				InputStream inputStream = entity.getContent();

				BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
				String line = null;
				while ((line = bReader.readLine()) != null) {
					sb.append(line);
				}
			} else {
				sb.append(reason);
			}
		} catch (UnsupportedEncodingException ex) {
		} catch (ClientProtocolException ex1) {
		} catch (IOException ex2) {
		}
		return sb.toString();
	}

	public  String getTwitterStream(String screenName) {
		String results = null;

		// Step 1: Encode consumer key and secret
		try {
			// URL encode the consumer key and secret
			String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
			String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");

			// Concatenate the encoded consumer key, a colon character, and the
			// encoded consumer secret
			String combined = urlApiKey + ":" + urlApiSecret;

			// Base64 encode the string
			String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

			// Step 2: Obtain a bearer token
			HttpPost httpPost = new HttpPost(TwitterTokenURL);
			httpPost.setHeader("Authorization", "Basic " + base64Encoded);
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
			String rawAuthorization = getResponseBody(httpPost);
			Authenticated auth = jsonToAuthenticated(rawAuthorization);

			// Applications should verify that the value associated with the
			// token_type key of the returned object is bearer
			if (auth != null && auth.token_type.equals("bearer")) {

				// Step 3: Authenticate API requests with bearer token
				HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);

				// construct a normal HTTPS request and include an Authorization
				// header with the value of Bearer <>
				httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
				httpGet.setHeader("Content-Type", "application/json");
				// update the results with the body of the response
				results = getResponseBody(httpGet);
			}
		} catch (UnsupportedEncodingException ex) {
		} catch (IllegalStateException ex1) {
		}
		return results;
	}
}

2.Use this parser class to Download feeds from server using the AsycTask.

MainActivity.java
package org.aynsoft.timeLine;

import org.aynsoft.java.InternetConnection;
import org.aynsoft.java.Parser;
import org.aynsoft.java.Twitter;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

	final static String ScreenName = "User_name";//user name of the usee
	final static String LOG_TAG = "ayn";
	private Parser parser;
	public static Twitter tweets;

	//Run when activity first create
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		parser=new Parser();	
		//download the tweets
		downloadTweets();
	}

	public void downloadTweets() {
		//check for the internet connection
		if (InternetConnection.checkNetworkConnection(getBaseContext())) {
			new DownloadTwitterTask().execute(ScreenName);
		} else {
			//Fires a toast and finish itself
			Toast.makeText(getBaseContext(), "No Internet Connection",
					Toast.LENGTH_SHORT).show();
			finish();
		}
	}

	private class DownloadTwitterTask extends AsyncTask<String, Void, String> {		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
		} 
		@Override
		protected String doInBackground(String... screenNames) {
			String result = null;
			if (screenNames.length > 0) {
				result = parser.getTwitterStream(screenNames[0]);
			}			
			return result;
		}
		@Override
		protected void onPostExecute(String result) {
			tweets = parser.jsonToTwitter(result);				
			//Tweets are ready do whatever
		}
	}
}

We have considerable experience in developing apps using Twitter API.

Over the years we have developed several advanced Twitter based Android and iPhone components, code modules and Frameworks that can work as plug and play solutions for developing new apps that will substantially reduce the app development cost and time.

Contact us to discuss your Twitter based mobile application development project

Google Maps for Android – Tutorial

Using Google Maps in Android Application includes several steps.

1. Install the Android SDK

As a prerequisite, you need to install the Android SDK. See Get the Android SDK.

2. Download and configure the Google Play services SDK, which includes the Google Maps Android API. If you use theGoogle Maps Mobile SDK for Business you must download and configure the Google Maps Mobile SDK for Business static library.

The Google Maps Android API v2 is distributed as part of the Google Play services SDK. You can download the Google Play services SDK via the Android SDK Manager.

To test your app when using the Google Play services SDK, you must use either:

  • A compatible Android device that runs Android 2.3 or higher and includes Google Play Store.
  • The Android emulator with an AVD that runs the Google APIs platform based on Android 4.2.2 or higher.
  • Add Google Play Services to Your Project
  • Create a Android Application Project.

Google Maps for Android

  • Import the Google Play Services into your workspace.

To import the Google Play Services into your workspace , first create a android project from existing resource.Then goto path ..sdk/extra/google/googleplayservice.

Google Maps for Android

Then copy the project in to the workspace..

  • Make this project as the library project of your project.
    Right Click on the project, then go to properties and the Android Section. Add google play service as library project.

Google Maps for Android

After you’ve added the Google Play services library as a dependency for your app project, open your app’s manifest file and add the following tag as a child of the element:

<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

3. Obtain an API key

Maps API keys are linked to specific certificate/package pairs, rather than to users or applications. You only need one key for each certificate, no matter how many users you have for an application. Applications that use the same certificate can use the same API key. However, the recommended practice is to sign each of your applications with a different certificate and get a different key for each one.

Obtaining a key for your application requires several steps.

  • Create key for your application

Google Maps for Android

Enter your SHA-1 fingerprint and the package of your application separated by a semicolon. For example you can use the org.aynsoft.mapDummy package.

Google Maps for Android

4. Add the API key to your application

Follow the steps below to include the API key in your application’s manifest, contained in the file AndroidManifest.xml. From there, the Maps API reads the key value and passes it to the Google Maps server, which then confirms that you have access to Google Maps data.

  • In AndroidManifest.xml, add the following element as a child of the element, by inserting it just before the closing tag :
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY"/>

Substitute your API key for API_KEY in the value attribute. This element sets the keycom.google.android.maps.v2.API_KEY to the value of your API key, and makes the API key visible to anyMapFragment in your application.

  • Save AndroidManifest.xml and re-build your application.

Specify permissions

Specify the permissions your application needs, by adding elements as children of the element. The syntax is:

<uses-permission android:name="permission_name"/>

For example, to request the Internet permission, add:

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

Besides permissions required by other parts of your application, you must add the following permissions in order to use the Google Maps Android API:

Google Maps Android API uses OpenGL ES version 2 to render the map

<uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

5. Add a Map

  • 1. Add the following fragment in the app’s layout XML file. If you created a ‘hello world’ app using the Android Developer Tools (ADT) package in Eclipse, the file is at res/layout/activity-main.xml. Replace the entire contents of that file with the following code.
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>
  • 1. Add the following code in MainActivity.java.
package com.example.mapdemo;

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

public class MainActivity extends Activity {

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

Build and run your application. You should see a map. If you don’t see a map, confirm that you’ve completed all the steps described on this page.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Over the years we have developed several Google Map, mashups Android and iPhone components, code modules and Frameworks that can work as plug and play solutions for developing new apps that will substantially reduce the app development cost and time.

Contact us to discuss your multimedia mobile application development project.

Mobile App Development Resources

If you are planning to start mobile app development, check out the links below. They are a collection of resources that you may need for iPhone app, Android App, Microsoft mobile app or HTML5 based app development.

Apple iOS, iPhone App development

iOS Development Center

https://developer.apple.com/devcenter/ios/index.action

Resources for Apple Developers

https://developer.apple.com/resources/

Getting started Tutorial

https://developer.apple.com/library/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html

Register as an Apple Developer

https://developer.apple.com/register/index.action

Xcode 6 – Toolset for building Apps

https://developer.apple.com/xcode/

iOS 7 SDK

https://developer.apple.com/ios7/

Swift is an innovative new programming language

https://developer.apple.com/swift/

iTunes – Apple Marketplace

http://www.apple.com/itunes/

Android App development

Official site provides information for users and developers

http://www.android.com/

Google Play Store

https://play.google.com/store

Provides documentation for App developer

http://developer.android.com/

Latest news and Android updates

https://plus.google.com/+android/posts

Download Android SDK

http://developer.android.com/sdk/index.html

Microsoft App development

Windows mobile development centre

http://msdn.microsoft.com/en-in/windowsmobile/bb264318.aspx

Getting Started with Windows Mobile Application Development

http://msdn.microsoft.com/en-in/windowsmobile/bb250560.aspx

Windows Mobile 6 SDK

http://www.microsoft.com/en-us/download/details.aspx?id=6135

Windows marketplace for Mobile

http://www.windowsphone.com/en-US/store

Get info on Windows Phones

http://www.windowsphone.com/en-us

Development Tools and Resources for Windows Mobile

http://msdn.microsoft.com/en-us/library/bb158509.aspx

Windows Phone Development Centre

https://dev.windowsphone.com/en-us

Top Mobile Frameworks:

Sencha Touch

JQuery Mobile

http://jquerymobile.com/

Ionic and AngularJS

http://ionicframework.com/

Kendo UI

http://www.telerik.com/

Appcelerator Titanium

http://www.appcelerator.com/

To add your link or for any other feedback, pl. Contact us.

Android App for USB Host (with source code)

Android App for USB Host (with source code)

Download APK Download Source Code Contact Us

When your Android-powered device is in USB host mode, it acts as the USB host, powers the bus, and enumerates connected USB devices. USB host mode is supported in Android 3.1 and higher.

Before you begin, it is important to understand the classes that you need to work with.

In most situations, you need to use all of these classes (UsbRequest is only required if you are doing asynchronous communication) when communicating with a USB device. In general, you obtain a UsbManager to retrieve the desired UsbDevice. When you have the device, you need to find the appropriate UsbInterface and the UsbEndpoint of that interface to communicate on. Once you obtain the correct endpoint, open aUsbDeviceConnection to communicate with the USB device.

Note:- In most of old phone USB hosting is not provided, only in new mobiles have inbuilt feature of USB Hosting. If you want to used it in old phones than you need to root your phone but it’s not advisable better you use USB Accessory in place of USB Host . it is similar to USB Host.

Here is a sample example to set USB Host in you android app
Layout Code: activity_main. Xml
When application is executed this is the first layout design that will run which will load width, height, load back ground details..etc.

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <button android:id="@+id/check"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Check USB devices"></button>
    <textview android:id="@+id/info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></textview>

</linearlayout>

Java File : MainActivity.java
MainActivity.java file in package com.mobilemerit.usbhost.
Main activity file will load design form like buttons, text view, on click functionality, display text.

package com.mobilemerit.usbhost;
import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.mobilemerit.usbhost.R;

public class MainActivity extends Activity {
	PendingIntent mPermissionIntent;
	Button btnCheck;
	TextView textInfo;
	UsbDevice device;
	UsbManager manager;
	private static final String ACTION_USB_PERMISSION = "com.mobilemerit.usbhost.USB_PERMISSION";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btnCheck = (Button) findViewById(R.id.check);
		textInfo = (TextView) findViewById(R.id.info);
		btnCheck.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				textInfo.setText("");
				checkInfo();
			}
		});

	}

	private void checkInfo() {
		manager = (UsbManager) getSystemService(Context.USB_SERVICE);
		/*
		 * this block required if you need to communicate to USB devices it's
		 * take permission to device
		 * if you want than you can set this to which device you want to communicate   
		 */
		// ------------------------------------------------------------------
		mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
				ACTION_USB_PERMISSION), 0);
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		registerReceiver(mUsbReceiver, filter);
		// -------------------------------------------------------------------
		HashMap<string , UsbDevice> deviceList = manager.getDeviceList();
		Iterator<usbdevice> deviceIterator = deviceList.values().iterator();
		String i = "";
		while (deviceIterator.hasNext()) {
			device = deviceIterator.next();
			manager.requestPermission(device, mPermissionIntent);
			i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
					+ "DeviceName: " + device.getDeviceName() + "\n"
					+ "DeviceClass: " + device.getDeviceClass() + " - "
					+ "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
					+ "VendorID: " + device.getVendorId() + "\n"
					+ "ProductID: " + device.getProductId() + "\n";
		}

		textInfo.setText(i);
	}

	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_USB_PERMISSION.equals(action)) {
				synchronized (this) {
					UsbDevice device = (UsbDevice) intent
							.getParcelableExtra(UsbManager.EXTRA_DEVICE);
					if (intent.getBooleanExtra(
							UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
						if (device != null) {
							// call method to set up device communication
						}
					} else {
						Log.d("ERROR", "permission denied for device " + device);
					}
				}
			}
		}
	};
}

Mainifest.xml

This is the main configuration file for USB Host android project. This xml code will load required permission and main activity by default.

< ?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mobilemerit.usbhost"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses -feature android:name="android.hardware.usb.host"></uses>
    <uses -sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="19"></uses>

<application android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name="com.mobilemerit.usbhost.MainActivity"
            android:label="@string/app_name" >
            <intent -filter>
                <action android:name="android.intent.action.MAIN"></action>

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

</manifest>

This is a simple code to find usb connected devices. If you need to communicate with usb device means send or receive data between your phone and usb device than you can other classes and interface (UsbInterface, UsbEndpoint, UsbDeviceConnection, UsbRequest).

Android App for USB Host
Android App for USB Host
Android App for USB Host

Download APK Download Source Code Contact Us