Hour 23. More Features to Explore

What You’ll Learn in This Hour:

Image Using Google Play services

Image Using Google Play services for location

Image Using open source

Image Using sensors, Bluetooth, and more

Professional apps are responsive, pay attention to detail, and include elegant finishing touches. A great Android app might use specific Android sensors such as the accelerometer or features such as Bluetooth or a location-based service. This hour begins with a discussion about how the features from Google Play services can be incorporated into your app. A demo app that uses Google Play services for determining location is developed. For other finishing touches, you learn about open source, Android sensors, and other features that may be used in your next great Android app.

Using Google Play Services

Google Play services is a library, really a set of libraries, that you can use in your apps. You can use Google Play services to add features such as location, maps, ads, Google Cloud Messaging, and more. For your app to be successful, Google Play services must be available on the user’s device. For apps that you publish in the Google Play store, that will not generally be a problem. However, if you plan on publishing on the Amazon App Store or other marketplaces, you must consider alternatives to use in those markets.

Setting Up Google Play Services

It is easy to set up and use Google Play services in Android Studio. You need to do two things:

1. First, add this line that refers to the Google Play Services library to your apps build.gradle file under dependencies:

compile 'com.google.android.gms:play-services:7.0.0'

2. Add the following to the Android manifest.xml file with the Application tag:

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

Alternatively, you can create a project in Android Studio that creates a Google Play services activity (see Figure 23.1).

Image

FIGURE 23.1 Creating a Google Play services activity.

Alternatively, you can just supply the library for the service you need. This a list of currently available services and what is required in the gradle build file. Note that you have already used the Android Wear service in Hour 22, “Android TV and Wear Apps.”

Image Google+: com.google.android.gms:play-services-plus:7.0.0

Image Google Account Login: com.google.android.gms:play-services-identity:7.0.0

Image Google Actions, Base Client Library: com.google.android.gms:play-services-base:7.0.0

Image Google App Indexing: com.google.android.gms:play-services-appindexing:7.0.0

Image Google Analytics: com.google.android.gms:play-services-analytics:7.0.0

Image Google Cast: com.google.android.gms:play-services-cast:7.0.0

Image Google Cloud Messaging: com.google.android.gms:play-services-gcm:7.0.0

Image Google Drive: com.google.android.gms:play-services-drive:7.0.0

Image Google Fit: com.google.android.gms:play-services-fitness:7.0.0

Image Google Location, Activity Recognition, and Places: com.google.android.gms:play-services-location:7.0.0

Image Google Maps: com.google.android.gms:play-services-maps:7.0.0

Image Google Mobile Ads: com.google.android.gms:play-services-ads:7.0.0

Image Google Nearby: com.google.android.gms:play-services-nearby:7.0.0

Image Google Panorama Viewer: com.google.android.gms:play-services-panorama:7.0.0

Image Google Play Game services: com.google.android.gms:play-services-games:7.0.0

Image SafetyNet: com.google.android.gms:play-services-safetynet:7.0.0

Image Google Wallet: com.google.android.gms:play-services-wallet:7.0.0

Image Android Wear: com.google.android.gms:play-services-wearable:7.0.0

You need to know the specifics of the Google Play service library that you plan on using, but you will always have to check to determine whether the services are available.

Checking for Google Play Services

Google Play services is based on the idea of connecting to the application programming interface (API) services. If you cannot connect, the services may not be available.

One way to check for availability is to implement an onConnectionFailed() listener.

A alternate way to check to see of Google Play services is available is to use the GooglePlayServicesUtil(com.google.android.gms.common.GooglePlayServicesUtil) and use the method isGooglePlayServicesAvailable().

You have to add these import statements:

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

Then you can add code to do the actual check. You will generally do that in the activity onStart() method:

@Override
    public void onStart() {
       super.onStart();
        int googlePlayResult =
            GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (googlePayResult == ConnectionResult.SUCCESS ) {
                // Start your services
        }else{
                   // handle the case when services are not available
        }
    }

Using Google Play Services for Location

Location-based services are an important part of Android development. There are classes built in to the Android platform that can be used for determining your location. Using Google Play services for location is both easy and very accurate. After covering some concepts about how location-based services work, you’ll develop an app that retrieves your current location information and tracks your location.

Determining Location

An Android device can obtain your current location in several ways. A global positioning system (GPS) uses satellite data to determine location. The underlying technique is triangulation. If you know your distance from three points, you can determine where you are. GPS relies on triangulating satellite data. If you are connected to a cellular network, the ID of the cell tower that the device is connected to provides your location. The Wi-Fi network that the device is attached to can also be used as the source of location information. Multiple companies, including Google, can tie a specific Wi-Fi network to a specific location.

Each method has advantages and disadvantages. Generally, you must balance the accuracy of GPS with the lower power consumption of the other methods:

Image GPS is accurate but might not work inside or with an obstructed view of the sky. It consumes a significant amount of power and causes battery drain.

Image Cell ID is less accurate than GPS, but consumes little power.

Image Wi-Fi might be very accurate depending on whether a network is recognized. It also consumes little power.

Using cell tower and Wi-Fi data together gives a more accurate location than either method alone, and Android has built-in support for this technique.

Android permissions for location-based services include a coarse location and a fine location. You must set these permissions to use location in your app:

Image android.permission.ACCESS_FINE_LOCATION: The permission to use GPS.

Image android.permission.ACCESS_COARSE_LOCATION: The permission to use the Android network provider. It uses both Wi-Fi and cell ID for location.

In the Android platform, a LocationManager(android.location.LocationManager) is used to access to system location services on the device and to request location updates. Location-based services rely heavily on the use of the LocationManager component.

A typical use case for LocationManager is to detect changes in location using GPS. To do that, you need to do the following:

1. Set android.permission.ACCESS_FINE_LOCATION.

2. Instantiate LocationManager.

3. Request location updates via GPS.

4. Listen for location changes.

That can be complicated and has limitations. In some cases, you might need to use the core location functionality. In many cases, however, you will be successful using Google Play services.

Implementing Location Tracking

To use location tracking with Google Play services, you use the library for location. From the list earlier in this hour, that means you can use the following:

com.google.android.gms:play-services-location:7.0.0

Listing 23.1 shows the entire code for an activity that uses Google Play services and displays current location. In the onStart() method in lines 31–42, a GoogleApiClient is defined. This is the Google Play services client. In line 36, the LocationServices.API is added as a service.

LISTING 23.1 Get Current Location with Google Play Services


 1: package com.talkingandroid.hour23application;
 2: import android.app.Activity;
 3: import android.os.Bundle;
 4: import android.location.Address;
 5: import android.location.Geocoder;
 6: import android.location.Location;
 7: import android.widget.TextView;
 8: import com.google.android.gms.common.ConnectionResult;
 9: import com.google.android.gms.common.api.GoogleApiClient;
10: import com.google.android.gms.location.LocationListener;
11: import com.google.android.gms.location.LocationRequest;
12: import com.google.android.gms.location.LocationServices;
13: import java.io.IOException;
14: import java.util.List;
15:
16: public class LocationActivity extends Activity implements  LocationListener,
17:         GoogleApiClient.ConnectionCallbacks,
18:         GoogleApiClient.OnConnectionFailedListener  {
19:
20:     TextView mDisplayTextView;
21:     LocationRequest mLocationRequest;
22:     private GoogleApiClient mGoogleApiClient;
23:
24:     @Override
25:     protected void onCreate(Bundle savedInstanceState) {
26:         super.onCreate(savedInstanceState);
27:         setContentView(R.layout.activity_location);
28:         mDisplayTextView = (TextView) findViewById(R.id.textView);
29:     }
30:
31:     @Override
32:     protected void onStart() {
33:         super.onStart();
34:         if (mGoogleApiClient == null) {
35:             mGoogleApiClient = new GoogleApiClient.Builder(this)
36:                     .addApi(LocationServices.API)
37:                     .addConnectionCallbacks(this)
38:                     .addOnConnectionFailedListener(this)
39:                     .build();
40:         }
41:         mGoogleApiClient.connect();
42:     }
43:
44:     @Override
45:     protected void onStop() {
46:         if (mGoogleApiClient != null) {
47:             mGoogleApiClient.disconnect();
48:         }
49:         super.onStop();
50:     }
51:
52:     @Override
53:     public void onConnected(Bundle connectionHint) {
54:         mLocationRequest = LocationRequest.create();
55:         LocationServices.FusedLocationApi.requestLocationUpdates
56:                        (mGoogleApiClient,mLocationRequest,this);
57:         Location location =
58:            LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
59:         mDisplayTextView.setText("Connected"
60:                     + location.getLatitude() +"," + location.getLongitude() );
61:     }
62:
63:     @Override
64:     public void onConnectionFailed(ConnectionResult arg0) {}
65:
66:     @Override
67:     public void onConnectionSuspended(int i) {}
68:
69:     @Override
70:    public void onLocationChanged(Location location) {
71:       Geocoder coder = new Geocoder(getApplicationContext());
72:        List<Address> geocodeResults;
73:      try {
74:            geocodeResults = coder.getFromLocation(location.getLatitude(),
75:                location.getLongitude(), 1);
76:             for (Address address: geocodeResults){
77:                 mDisplayTextView.setText("Update: "
78:                   + location.getLatitude() +","
79:                  + location.getLongitude()+" : " +address.getLocality());
80:            }
81:
82:         } catch (IOException e) {
83:             e.printStackTrace();
84:         }
85:     }
86: }


In lines 16–18, the activity extends three classes:

Image LocationListener: To listen for location changes

Image GoogleApiClient.ConnectionCallbacks: To fire when Google Play services connects

Image GoogleApiClient.OnConnectionFailedListener: To fire if Google Play services fails

The onConnected() method is on line 53. Code that relies on a connection to Google Play services should be placed in the onConnected() method.

It is in the onConnected() method that the location services are created and used. The LocationListener is specified as this on line 56. That means that the current activity is the LocationListener.

The activity implements the onLocationChanged() method, so it is a LocationListener. The onLocation() changed code updates a TextView on any location changes.

Figure 23.2 shows a screenshot of that app.

Image

FIGURE 23.2 Simple location app.

The permission android.permission.ACCESS_FINE_LOCATION is set.

Using Open Source and External SDKs

You have used the Picasso project to load images. Picasso was developed at Square. Square and other companies have made it a practice to develop and release open source projects that can be very helpful to your development efforts.

Using open source libraries is common for individual developers and many companies. Most open source code includes a specific license regarding usage. Many are released under the Apache 2.0 license. You can find more information about that license at http://www.apache.org/licenses/. The FAQ section includes an explanation of the license for nonlawyers.

The following sections describe each of these briefly. These projects and other open source projects can help you make better apps.

Picasso

Handling images in Android might not always be straightforward. The goal of Picasso is to handle working with images and image views in an elegant way. It handles disk caching and memory caching of images and keeps overall memory usage to a minimum. Much of the “plumbing” of handling images is kept behind the scenes.

Loading an image from a URL using Picasso is done with one line:

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Realm

Realm (https://github.com/realm/realm-java) is a mobile database for Android. It is a modern replacement for SQLite.

Fabric and Crashlytics

Fabric (https://get.fabric.io/) is a set of tools from Twitter. It includes Crashlytics, which is a software development kit (SDK) for collecting meaningful data when an app crashes. Fabric includes Twitter integration and ad opportunities. Fabric is not completely open source!

Digging Deeper into Android

Hopefully this is not a surprise, but 24 hours is not enough time to cover all the interesting and useful features of the Android platform and Android SDK. You’ve worked on many applications and features over the course of this book.

With the knowledge you have acquired thus far, you might find yourself thinking about your own application ideas. The rest of this hour covers some additional Android features that might help with your applications and point you in the right direction for using the features in your own application.

The Android developer documentation is a good starting point for further exploration of these topics: http://developer.android.com/.

Using Sensors

Sensors can add interesting and unique features to your app. Android devices come with hardware and software sensors and not all devices will have all sensors. That means that one thing to know about sensors in general is that your app has to check to see whether they exist on a user’s device.

This snippet of code checks for the accelerometer sensor:

private SensorManager mSensorManager;
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(TYPE_ACCELEROMETER) != null){
  // Sensor is available
} else {
  // Sensor is not available
}

Working with sensors takes a common approach. Like many things in Android, when working with a sensor, you set up a listener and listen for changes produced by the sensor. There is a SensorEventListener(android.hardware.SensorEventListener) class for this purpose. A SensorEventListener implements the onSensorChanged() method to listen for SensorEvents(android.hardware.SensorEvent). From the SensorEvent, you can determine the sensor that generated the event and data associated with the event.

The following are some of the device sensors that the Android SDK supports:

Image Accelerometer: Measures acceleration in three dimensions

Image Light sensor: Measures ambient brightness

Image Magnetic field sensor: Measures earth’s magnetic field in three dimensions

Image Orientation sensor: Measures a device’s orientation

Image Temperature sensor: Measures ambient temperature

Image Proximity sensor: Measures whether there is something near the screen of the device

Handling User Gestures

You already know how to listen for click events. You can also handle gestures, such as flings, scrolls, and taps, by using the GestureDetector class (android.view.GestureDetector). You can use the GestureDetector class by implementing the onTouchEvent() method within an activity.

The following are some of the gestures an application can watch for and handle:

Image onDown: Occurs when the user first presses the touch screen.

Image onShowPress: Occurs after the user first presses the touch screen but before the user lifts up or moves around on the screen.

Image onSingleTapUp: Occurs when the user lifts up from the touch screen as part of a single-tap event.

Image onSingleTapConfirmed: Called when a single-tap event occurs.

Image onDoubleTap: Called when a double-tap event occurs.

Image onDoubleTapEvent: Called when an event within a double-tap gesture occurs, including any down, move, or up action.

Image onLongPress: Similar to onSingleTapUp, but called if the user has held his or her finger down just long enough to not be a standard click but also didn’t move the finger.

Image onScroll: Called after the user has pressed and then moved his or her finger in a steady motion and lifted up.

Image onFling: Called after the user has pressed and then moved his or her finger in an accelerating motion just before lifting it.

In addition, the android.gesture package enables an application to recognize arbitrary gestures and to store, load, and draw them. This means that almost any symbol a user can draw could be turned into a gesture with a specific meaning.

Customizing Styles and Themes

The Android SDK provides two powerful mechanisms for designing consistent user interfaces that are easy to maintain: styles and themes. You have used themes in the project that you have developed, but you have not customized themes to use in your app.

A style is a grouping of common view attribute settings that you can apply to any number of view controls. For example, you might want all view controls in your application, such as TextView and EditText controls, to use the same text color, font, and size. You could create a style that defines these three attributes and apply it to each TextView and EditText control within your application layouts.

A theme is a collection of one or more styles. Whereas you apply a style to a specific control, such as a TextView control, you apply a theme to all View objects within a specified activity. Applying a theme to a set of View objects all at once simplifies making the user interface look consistent. It can be a great way to define color schemes and other common view attribute settings across an application. You can also apply themes in the Android manifest file.

Designing Custom View and ViewGroup Controls

You are already familiar with many of the user interface controls, such as Layout and View controls that are available in the Android SDK. You can also create custom controls. To do so, you start with the appropriate View (or ViewGroup) control from the android.view package and implement the specific functionality needed for your control or layout.

You can use custom View controls in XML layout files, or you can inflate them programmatically at runtime. You can create new types of controls, or you can extend the functionality of existing controls, such as TextView or Button controls.

The Facebook LoginButton is an example of a custom view, but often custom views are simple extensions of basic views.

Camera

Android has an extensive camera application programming interface (API). Each release of Android adds more features. Android 5.0 added significant new capabilities to controlling the camera.

Using the OpenGL ES Graphics API

For more advanced graphics, Android uses the popular OpenGL ES graphics API. OpenGL ES 1.0 has been supported since Android 1.0. In Android 5.0, OpenGL ES 3.1 support was added. Applications can use Android’s OpenGL ES support to draw, animate, light, shade, and texture graphical objects in three dimensions.

Bluetooth

Bluetooth support was included on Android 2.0. With Android 4.3, Android has added support for Bluetooth low energy (LE). Bluetooth LE makes it possible to build Android apps that communicate with Bluetooth LE peripheral devices. For example, a phone that includes Bluetooth LE support that is running Android 4.3 could support an app that interacts with a pedometer.

Android 4.3 introduced the BluetoothManager(android.bluetooth.BluetoothManager) class to help an app handle Bluetooth management.

Android 5.0 added additional Bluetooth (LE) API calls.

NFC and Beam

Most Android phones have near-field communication (NFC) capability. That means that they can communicate in short messages from an NFC tag when the phone is very close to the tag. NFC is a set of short-range wireless technologies.

A set of NFC intents is defined in Android. When a tag is read, these intents are fired. The idea is to create an app that filters for these intents and launches when an NFC tag is read. The details of NFC tags and the relationship between the tags and the application that is launched can get complicated. NFC concepts are covered in the Android developer documentation.

Android Beam is a technology for peer-to-peer NFC communication, which means that two Android devices can communicate through NFC using this technology.

Android 5.0 added API calls to make NFC easier to use as a developer.

Summary

In this hour, you learned about adding additional features to your app through the use of Google Play services and open source libraries. In addition, this hour reviewed Android features such as sensors, graphics, camera, Bluetooth, and NFC.

Q&A

Q. With the contents of this hour, have we covered everything available in Android?

A. No, this book has covered much of the Android system and includes topics such as the use of SQLite, content providers, and more that are commonly used in Android, but it is not an encyclopedic view of Android. The goal of this hour was to cover features that are often used in production-level Android apps and to be a guide to new topics.

Q. What happens when new features are added in Android?

A. New features provide new opportunities for developers. Often we need to develop an app for as many people as possible, but developing an app with new capabilities that relies on the latest Android features might provide a good opportunity to create an app that gets noticed and used.

Workshop

Quiz

1. What is Realm?

2. True or false: Google Play services are built in to every Android device.

3. What method must be implemented for a location listener?

Answers

1. Realm is an open source Android database.

2. False. You must check to see whether Google Play services are installed.

3. If you use a location listener, you must implement onLocationChanged().

Exercise

Create an Android app that uses any Google Play service. You can re-create the location service that is used in this hour or research another service to implement. In this hour, you learned about the structure of an app that uses Google Play services, and you used the location service. When you use other services, you must refer to the specific API calls that are used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.167.114