• No results found

Now that you have followed all the steps above, it’s time to create the app. Create a new project and give it a name. The next step is to add the Google play service to the project.

To do this, just select the project and right click on it. Choose Build Path > Configure Build Path > Android > Add. Double click on the Google_play_service_lib which will be shown.

Modify the class activity_main.xml to the following:

<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”

android:layout_width=“fill_parent”

android:layout_height=“fill_parent”

android:orientation=“vertical” >

<Button android:id=”@+id/loc”

android:layout_width=“fill_parent”

android:layout_height=“wrap_content”

android:text=“Get Location”/>

<Button android:id=”@+id/dscon”

android:layout_width=“fill_parent”

android:layout_height=“wrap_content”

android:text=“Disconnect Service”/>

<Button android:id=”@+id/cnt”

android:layout_width=“fill_parent”

android:layout_height=“wrap_content”

android:text=“Connect Service”/>

<TextView

android:id=”@+id/locationLabel”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”/>

<TextView

android:id=”@+id/labaddress”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”/>

</LinearLayout>

Modify the class MainActivity.java to the following:

import java.util.List;

import java.io.IOException;

import java.util.Locale;

import com.google.android.gms.common.GooglePlayServicesClient;

import com.google.android.gms.common.ConnectionResult;

import com.google.android.gms.location.LocationClient;

import android.location.Address;

import android.content.Context;

import android.os.AsyncTask;

import android.location.Geocoder;

import android.os.Bundle;

import android.location.Location;

import android.support.v4.app.FragmentActivity;

import android.util.Log;

import android.widget.Button;

import android.view.View;

import android.widget.Toast;

import android.widget.TextView;

public class MainActivity extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks,

GooglePlayServicesClient.OnConnectionFailedListener {

LocationClient mloc;

private TextView labeladdress;

private TextView labelloc;

private Button locbtn;

private Button disbtn;

private Button conBtn;

@Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

labelloc = (TextView) findViewById(R.id.locationlabel);

labeladdress = (TextView) findViewById(R.id.labaddress);

locbtn = (Button) findViewById(R.id.loc);

locbtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {

displayCurrentLocation();

} });

disbtn = (Button) findViewById(R.id.dscon);

disbtn.setOnClickListener(new V.OnClickListener() { public void onClick(View v) {

mLoc.disconnect();

labelloc.setText(“you are disconnected….”);

} });

conbtn = (Button) findViewById(R.id.cnt);

conbtn.setOnClickListener(new V.OnClickListener() { public void onClick(View v) {

mLoc.connect();

labelloc.setText(“you are connected….”);

}

});

mLoc = new LocationClient(this, this, this);

}

@Override

protected void onStart() { super.onStart();

// Connection to the client.

Loc.connect();

labelloc.setText(“you are connected….”);

}

@Override

protected void onStop() {

// Disconnection from the client.

mLoc.disconnect();

super.onStop();

labelloc.setText(“you are disconnected….”);

}

@Override

public void onConnected(Bundle datamb) { // Display the connection status

Toast.makeText(this, “Connected”, Toast.LENGTH_SHORT).show();

}

@Override

public void onDisconnected() { // show the status of connection

Toast.makeText(this, “Try to reconnect, you are disconnected.”, Toast.LENGTH_SHORT).show();

}

@Override

public void onConnectionFailed(ConnectionResult conResult) { // show the error code if failure occurs

Toast.makeText(this, “Failure in connection : ” + conResult.getErrorCode(),

Toast.LENGTH_SHORT).show();

}

public void displayCurrentLocation() {

// Get the longitude and latitude of the current location Location currLoc = mLoc.getLastLocation();

String message = “Current Location: ” +

Double.toString(currLoc.getLatitude()) + “,” + Double.toString(currLoc.getLongitude());

// current location will be shown on the screen labelloc.setText(message);

// To show current address on the device’s screen (new GetAddressTask(this)).execute(currLoc);

} /*

This will give the address as per the current latitude and longitude. It is a subclass of AsyncTask

*/

private class GetAddressTask extends AsyncTask<Location, Void, String>{

Context mc;

public GetAddressTask(Context c) { super();

mc = c;

}

/*

* the onPostExposure will display the address when the task is *finished.

*/

@Override

protected void onPostExecute(String a) { // show the current address on the screen

labaddress.setText(a);

}

@Override

protected String doInBackground(Location… params) { Geocoder gcoder =

new Geocoder(mc, Locale.getDefault());

// getting the current location from the inputted parameter list Location lc = params[0];

// Creating a list for containing the addresses List<Address> ads = null;

try {

ads = gcoder.getFromLocation(lc.getLatitude(), lc.getLongitude(), 1);

} catch (IOException e1) {

Log.e(“LocationSampleActivity”,

“IO Exception in getFromLocation()”);

e1.printStackTrace();

return (“IO Exception occurred in getting the address”);

} catch (IllegalArgumentException e2) { // Error message to be posted in the log

String errorMessage = “Wrong arguments ” +

Double.toString(lc.getLatitude()) +

” , ” +

Double.toString(lc.getLongitude()) +

” already passed to address service”;

Log.e(“LocationSampleActivity”, errorMessage);

e2.printStackTrace();

return errorString;

}

// If the a address is returned by the reverse geocode if (ads != null && ads.size() > 0) {

// Obtain the first address Address a = ads.get(0);

/*

* Formatting the first line of the address if available

*/

String aText = String.format(

“%s, %s, %s”,

// adding a street address if it is available.

a.getMaxAddressLineIndex() > 0 ? a.getAddressLine(0) : ””,

// A city is usually the locality

a.getLocality(),

// getting the addresse’s country a.getCountryName());

// returning the value of text return aText;

} else {

return “Didn’t find any address”;

} }

}// AsyncTask class }

The string.xml file should be modified to the following:

<?xml version=“1.0” encoding=“utf-8”?>

<resources>

<string name=“app_name”>LocationBasedServicesDemo</string>

<string name=“action_settings”>Settings</string>

<string name=“hello_world”>Hello world!</string>

<string name=“loc”>Get Location</string>

<string name=“dscon”>Disconnect Service</string>

<string name=“cnt”>Connect Service</string>

</resources>

The AndroidManifest.xml file should be modified to the following:

<?xml version=“1.0” encoding=“utf-8”?>

<manifest xmlns:android=“http://schemas.android.com/apk/res/android”

package=“com.example. LocationBasedServicesDemo “ android:versionCode=“1”

android:versionName=“1.0” >

<uses-sdk

android:minSdkVersion=“8”

android:targetSdkVersion=“17” />

<uses-permission

android:name=“android.permission.ACCESS_COARSE_LOCATION”/>

<application

android:allowBackup=“true”

android:icon=”@drawable/ic_launcher”

android:label=”@string/app_name”

android:theme=”@style/AppTheme” >

<activity

android:name=“com.example. LocationBasedServicesDemo.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>

That is what it entails to work with location based services in android. The most important thing is to install the Google play service SDK and the rest will be easy. It is better to use a real device when running the above app, since the emulator may lack the necessary

features. Your SDK should also be updated to the latest version, otherwise you will get

errors.

Related documents