Abstract
This case study discusses building map and geolocation features into an Android* business app, which includes overlaying store locations on Google Maps*, using geofence to notify the user when the device enters the store proximities.
Table of Contents
- Abstract
- Overview
- Displaying Store Locations on Google Maps
- Google Maps Android API v2
- Specifying App Settings in the Application Manifest
- Adding a Map Fragment
- Sending Geofence Notifications
- Registering and Unregistering Geofences
- Implementing the Location Service Callbacks
- Implementing the Intent Service
- Summary
- References
- About the Authors
Overview
In this case study, we will incorporate maps and geolocation functionality into a restaurant business app for Android tablets (Figure 1). The user can access the geolocation functionality from the main menu item "Locations and Geofences" (Figure 2).
Figure 1 The Restaurant App Main Screen
Figure 2 The Flyout Menu Items
Displaying Store Locations on Google Maps
For a business app, showing the store locations on maps is very graphical and helpful to the user (Figure 3). The Google Maps Android API provides an easy way to incorporate Google Maps into your Android apps.
Google Maps Android API v2
Google Maps Android API v2 is part of the Google Play Services APK. To create an Android app which uses the Google Maps Android API v2 requires setting up the development environment by downloading and configuring the Google Play services SDK, obtaining an API key, and adding the required settings in your app’s AndroidManifest.xml file.
First you need to set up Google Play Services SDK by following http://developer.android.com/google/play-services/setup.html.
Then you register your project and obtain an API key from Google Developers Console https://console.developers.google.com/project. You will need to add the API key in your AndroidManifest.xml file.
Figure 3 The Restaurant App Shows Store Locations on Google Maps.
Specifying App Settings in the Application Manifest
To use Google Maps Android API v2, some permissions and features are required to be specified as children of the <manifest> element (Code Example 1). They include the necessary permissions for network connection, external storage, and access to the location. Also OpenGL ES version 2 feature is needed for the Google Maps Android API.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<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"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
Code Example 1. Recommended permissions to specify for an app which uses Google Maps Android API. Include the "ACCESS_MOCK_LOCATION" permission only if you test your app with mock locations **
Also as children of the <application> element, we specify the Google Play Services version and the API key we obtained in <meta-data> elements (Code Example 2).
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="copy your API Key here"/>
Code Example 2. Specify Google Play Services Version and API Key **
Adding a Map Fragment
First in your activity layout xml file, add a MapFragment element (Code Example 3).
<fragment
android:id="@+id/storelocationmap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:name="com.google.android.gms.maps.MapFragment"
/>
Code Example 3. Add a MapFragment in the Activity Layout **
In your activity class, you can retrieve the Google Maps MapFragment object and draw the store icons at each store location.
…
private static final LatLng CHANDLER = new LatLng(33.455,-112.0668);
…
private static final StoreLocation[] ALLRESTURANTLOCATIONS = new StoreLocation[] {
new StoreLocation(new LatLng(33.455,-112.0668), new String("Phoenix, AZ")),
new StoreLocation(new LatLng(33.5123,-111.9336), new String("SCOTTSDALE, AZ")),
new StoreLocation(new LatLng(33.3333,-111.8335), new String("Chandler, AZ")),
new StoreLocation(new LatLng(33.4296,-111.9436), new String("Tempe, AZ")),
new StoreLocation(new LatLng(33.4152,-111.8315), new String("Mesa, AZ")),
new StoreLocation(new LatLng(33.3525,-111.7896), new String("Gilbert, AZ"))
};
…
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geolocation_view);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.storelocationmap)).getMap();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CHANDLER, ZOOM_LEVEL));
Drawable iconDrawable = getResources().getDrawable(R.drawable.ic_launcher);
Bitmap iconBmp = ((BitmapDrawable) iconDrawable).getBitmap();
for(int ix = 0; ix < ALLRESTURANTLOCATIONS.length; ix++) {
mMap.addMarker(new MarkerOptions()
.position(ALLRESTURANTLOCATIONS[ix].mLatLng)
.icon(BitmapDescriptorFactory.fromBitmap(iconBmp)));
}
…
Code Example 4. Draw the Store Icons on Google Maps **
A geofence is a circular area defined by the latitude and longitude coordinates of a point and a radius. An Android app can register geofences with the Android Location Services. The Android app can also specify an expiration duration for a geofence. Whenever a geofence transition happens, for example, when the Android device enters or exits a registered geofence, the Android Location Services will inform the Android app.
In our Restaurant app, we can define a geofence for each store location. When the device enters the proximity of the store, the app sends a notification for example, "You have entered the proximity of your favorite restaurant!" (Figure 4).
Figure 4 A geofence is defined as a circular area by a point of interest and a radius
Registering and Unregistering Geofences
In Android SDK, Location Services is also part of Google Play services APK under the "Extras" directory.
To request geofence monitoring, first we need to specify the "ACCESS_FINE_LOCATION" permission in the app’s manifest, which we have already done in the previous sections.
We also need to check the availability of the Google Play Services (the checkGooglePlayServices()
method in Code Example 5). After the locationClient().connect()
call and the location client has successfully established a connection, the Location Services will call the onConnected(Bundle bundle)
function, where the location client can request adding or removing geofences.
public class GeolocationActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks
…
{
…
private LocationClient mLocationClient;
…
static class StoreLocation {
public LatLng mLatLng;
public String mId;
StoreLocation(LatLng latlng, String id) {
mLatLng = latlng;
mId = id;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geolocation_view);
mLocationClient = new LocationClient(this, this, this);
mGeofenceBroadcastReceiver = new ResturantGeofenceReceiver();
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(ACTION_GEOFENCES_ADDED);
mIntentFilter.addAction(ACTION_GEOFENCES_REMOVED);
mIntentFilter.addAction(ACTION_GEOFENCE_ERROR);
mIntentFilter.addCategory(CATEGORY_LOCATION_SERVICES);
createGeofences();
mRegisterGeofenceButton = (Button)findViewById(R.id.geofence_switch);
mGeofenceState = CAN_START_GEOFENCE;
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(
mGeofenceBroadcastReceiver, mIntentFilter);
}
public void createGeofences() {
for(int ix=0; ix > ALLRESTURANTLOCATIONS.length; ix++) {
Geofence fence = new Geofence.Builder()
.setRequestId(ALLRESTURANTLOCATIONS[ix].mId)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.setCircularRegion(
ALLRESTURANTLOCATIONS[ix].mLatLng.latitude, ALLRESTURANTLOCATIONS[ix].mLatLng.longitude, GEOFENCERADIUS)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
mGeofenceList.add(fence);
}
}
public void onRegisterGeofenceButtonClick(View view) {
if (mGeofenceState == CAN_REGISTER_GEOFENCE) {
registerGeofences();
mGeofenceState = GEOFENCE_REGISTERED;
mGeofenceButton.setText(R.string.unregister_geofence);
mGeofenceButton.setClickable(true);
else {
unregisterGeofences();
mGeofenceButton.setText(R.string.register_geofence);
mGeofenceButton.setClickable(true);
mGeofenceState = CAN_REGISTER_GEOFENCE;
}
}
private boolean checkGooglePlayServices() {
int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (result == ConnectionResult.SUCCESS) {
return true;
}
else {
Dialog errDialog = GooglePlayServicesUtil.getErrorDialog(
result,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
if (errorDialog != null) {
errorDialog.show();
}
}
return false;
}
public void registerGeofences() {
if (!checkGooglePlayServices()) {
return;
}
mRequestType = REQUEST_TYPE.ADD;
try {
requestConnectToLocationClient();
} catch (UnsupportedOperationException e) {
}
}
public void unregisterGeofences() {
if (!checkGooglePlayServices()) {
return;
}
mRequestType = REQUEST_TYPE.REMOVE;
try {
mCurrentIntent = getRequestPendingIntent());
requestConnectToLocationClient();
} catch (UnsupportedOperationException e) {
}
}
public void requestConnectToLocationServices () throws UnsupportedOperationException {
if (!mRequestInProgress) {
mRequestInProgress = true;
locationClient().connect();
}
else {
throw new UnsupportedOperationException();
}
}
private void requestDisconnectToLocationServices() {
mRequestInProgress = false;
locationClient().disconnect();
if (mRequestType == REQUEST_TYPE.REMOVE) {
mCurrentIntent.cancel();
}
}
private GooglePlayServicesClient locationClient() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(this, this, this);
}
return mLocationClient;
}
@Override
public void onConnected(Bundle bundle) {
if (mRequestType == REQUEST_TYPE.ADD) {
mGeofencePendingIntent = createRequestPendingIntent();
mLocationClient.addGeofences(mGeofenceList, mGeofencePendingIntent, this);
}
else if (mRequestType == REQUEST_TYPE.REMOVE){
mLocationClient.removeGeofences(mCurrentIntent, this);
}
}
…
}
Code Example 5. Request Geofence Monitoring by Location Services **
Implementing the Location Service Callbacks
The location service requests are usually non-blocking or asynchronous calls. Actually in Code Example 5 in the previous section, we have already implemented one of these functions: after the locationClient().connect()
call and the location client establishes a connection, the Location Services will call the onConnected(Bundle bundle)
function. Code Example 6 lists other location callback functions we need to implement.
public class GeolocationActivity extends Activity implements
OnAddGeofencesResultListener,
OnRemoveGeofencesResultListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
…
@Override
public void onDisconnected() {
mRequestInProgress = false;
mLocationClient = null;
}
@Override
public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {
Intent broadcastIntent = new Intent();
String msg;
if (LocationStatusCodes.SUCCESS == statusCode) {
msg = getString(R.string.add_geofences_result_success,
Arrays.toString(geofenceRequestIds));
broadcastIntent.setAction(ACTION_GEOFENCES_ADDED)
.addCategory(CATEGORY_LOCATION_SERVICES)
.putExtra(EXTRA_GEOFENCE_STATUS, msg);
} else {
msg = getString(
R.string.add_geofences_result_failure,
statusCode,
Arrays.toString(geofenceRequestIds)
);
broadcastIntent.setAction(ACTION_GEOFENCE_ERROR)
.addCategory(CATEGORY_LOCATION_SERVICES)
.putExtra(EXTRA_GEOFENCE_STATUS, msg);
}
LocalBroadcastManager.getInstance(this)
.sendBroadcast(broadcastIntent);
requestDisconnectToLocationServices();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
mInProgress = false;
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
}
catch (SendIntentException e) {
}
}
else {
Intent errorBroadcastIntent = new Intent(ACTION_CONNECTION_ERROR);
errorBroadcastIntent.addCategory(CATEGORY_LOCATION_SERVICES)
.putExtra(EXTRA_CONNECTION_ERROR_CODE,
connectionResult.getErrorCode());
LocalBroadcastManager.getInstance(this)
.sendBroadcast(errorBroadcastIntent);
}
}
@Override
public void onRemoveGeofencesByPendingIntentResult(int statusCode,
PendingIntent requestIntent) {
Intent broadcastIntent = new Intent();
if (statusCode == LocationStatusCodes.SUCCESS) {
broadcastIntent.setAction(ACTION_GEOFENCES_REMOVED);
broadcastIntent.putExtra(EXTRA_GEOFENCE_STATUS,
getString(R.string.remove_geofences_intent_success));
}
else {
broadcastIntent.setAction(ACTION_GEOFENCE_ERROR);
broadcastIntent.putExtra(EXTRA_GEOFENCE_STATUS,
getString(R.string.remove_geofences_intent_failure,
statusCode));
}
LocalBroadcastManager.getInstance(this)
.sendBroadcast(broadcastIntent);
requestDisconnectToLocationServices();
}
public class ResturantGeofenceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (TextUtils.equals(action, ACTION_GEOFENCE_ERROR)) {
}
else if (TextUtils.equals(action, ACTION_GEOFENCES_ADDED)
||
TextUtils.equals(action, ACTION_GEOFENCES_REMOVED)) {
}
else if (TextUtils.equals(action, ACTION_GEOFENCE_TRANSITION)) {
}
else {
}
}
}
public PendingIntent getRequestPendingIntent() {
return createRequestPendingIntent();
}
private PendingIntent createRequestPendingIntent() {
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
} else {
Intent intent = new Intent(this,
ReceiveGeofenceTransitionIntentService.class);
return PendingIntent.getService(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
}
@Override
public void onRemoveGeofencesByRequestIdsResult(int statusCode,
String[] geofenceRequestIds) {
requestDisconnection();
}
Code Example 6. IImplement the Location Service Callbacks **
Implementing the Intent Service
Finally, we need to implement the IntentService class to handle the geofence transitions (Code Example 7).
public class ReceiveGeofenceTransitionIntentService extends IntentService {
public ReceiveGeofenceTransitionIntentService() {
super("ReceiveGeofenceTransitionsIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Intent broadcastIntent = new Intent();
broadcastIntent.addCategory(CATEGORY_LOCATION_SERVICES);
if (LocationClient.hasError(intent)) {
int errorCode = LocationClient.getErrorCode(intent);
}
else {
int transition =
LocationClient.getGeofenceTransition(intent);
if ((transition == Geofence.GEOFENCE_TRANSITION_ENTER) ||
(transition == Geofence.GEOFENCE_TRANSITION_EXIT)) {
}
else {
}
}
}
}
Code Example 7. Implement an IntentService Class to Handle Geofence Transitions
Summary
In this article, we have discussed how to incorporate mapping and geofencing features into an Android business app. These features support rich geolocation contents and strong location based services and use cases in your apps.
References
About the Author
Miao Wei is a software engineer in the Intel Software and Services Group. He currently works on the Intel® Atom™ processor scale enabling projects.
*Other names and brands may be claimed as the property of others.
**This sample source code is released under the Intel Sample Source Code License Agreement
Optimization Notice
Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel.
Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice.
Other Related Articles and Resources