Android UI(8)Building Apps with User Info&Location

Android UI(8)Building Apps with User Info&Location

1. Accessing Contacts Data
…snip…

2. Remembering Users
…snip...

3. Making Your App Location Aware
Download the sample code LocationAware.zip.

3.1 Using the Location Manager
Declare Proper Permissions in Android Manifest
    <uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/>

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

Get a Reference to LocationManager
// Get a reference to the LocationManager object.

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

Pick a Location Provider
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);finalboolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

3.2 Obtaining the Current Location
Set Up the Location Listener
private final LocationListener listener = new LocationListener() {
public void onLocationChanged(Location location) {     updateUILocation(location);}public void onProviderDisabled(String provider) {}public void onProviderEnabled(String provider) {}public void onStatusChanged(String provider, int status, Bundle extras) {}

};

private Location requestUpdatesFromProvider(final String provider,final String errorResId) {
Location location = null;if (locationManager.isProviderEnabled(provider)) {     locationManager.requestLocationUpdates(provider, TEN_SECONDS,TEN_METERS, listener);     location = locationManager.getLastKnownLocation(provider);} else {     Toast.makeText(this, errorResId, Toast.LENGTH_LONG).show();}return location;

}


gpsLocation = requestUpdatesFromProvider(LocationManager.GPS_PROVIDER,"GPS provider is not supported.");networkLocation = requestUpdatesFromProvider(LocationManager.NETWORK_PROVIDER,"Network provider is not supported.");


Handle Multiple Sources of Location Updates
…snip...
Terminate Location Updates
locationManager.removeUpdates(listener);


3.3 Displaying the Location Address
It is not working on my device. I do not know if it is working on other device.
geocoderAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();
private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
Context context;public ReverseGeocodingTask(Context context) {     super();     this.context = context;}protected Void doInBackground(Location... params) {Geocoder geocoder = new Geocoder(context, Locale.getDefault());Location loc = params[0];List<Address> addresses = null;try {     addresses = geocoder.getFromLocation(loc.getLatitude(),loc.getLongitude(), 1);} catch (IOException e) {     e.printStackTrace();     // Update address field with the exception.     Message.obtain(handler, UPDATE_ADDRESS, e.toString()).sendToTarget();}if (addresses != null && addresses.size() > 0) {     Address address = addresses.get(0);     String addressText = String.format(          "%s, %s, %s",     address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", address.getLocality(),     address.getCountryName());// Update address field on UI.     Message.obtain(handler, UPDATE_ADDRESS, addressText).sendToTarget();}return null;}

}



Tips:
1. LocationManager addProximityAlert
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Intent intent = new Intent("com.sillycat.easyrestclientandroid");
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, -1, intent,0);
locationManager.addProximityAlert(lat,lng,radius,expiration,proximityIntent);

public class ProximityIntentReceiver extends BroadcastReceiver{
     public void onReceive(Context context, Intent intent){
          String key = LocationManager.KEY_PROXIMITY_ENTERING;
          boolean entering = intent.getBooleanExtra(key,false);
          …snip...
     }
}

IntentFilter filter = new IntentFilter("com.sillycat.easyrestclientandroid");
registerReceiver(new ProximityIntentReceiver(),fitler);

2. Android android.app.Service
http://developer.android.com/reference/android/app/Service.html
The lifecycle of Service will be onCreate(), onStart(), onDestroy()
During start ----- onCreate(), onStart(), if the second time to start this service, it will only call onStart()
During stop ----- onDestroy()

There is no UI for service, but it should be always running background.

There are 2 ways to start the Service, Context.startService(), Context.bindService().

Context.startService()
startService ----  onCreate() -----> onStart()         Second Time, only onStart()
stopService ----  onDestroy()

If the system did not destroy the service and quit the application, the service will be running on the backend. After we start the service we can check how many services we have in the [Setting] --> [Applications] --> Running Services

Context.bindService()
bindService ---> onCreate() ---> onBind()             Second Time, nothing
unbindService ----> onUnbind() ---> onDestory()

onStartCommand
this onStartCommand() will be called after we invoke startService(Intent)

References:
http://developer.android.com/training/building-userinfo.html
http://developer.android.com/training/id-auth/index.html
http://developer.android.com/training/basics/location/index.html

Google Sample
https://code.google.com/p/google-api-java-client/wiki/APIs
https://code.google.com/p/google-api-java-client/source/browse/tasks-android-sample/src/main/java/com/google/api/services/samples/tasks/android/TasksSample.java?repo=samples
https://developers.google.com/google-apps/tasks/oauth-and-tasks-on-android

Android Service
http://blog.sina.com.cn/s/blog_3fe961ae0100xhsl.html
http://blog.csdn.net/nkmnkm/article/details/7331297

猜你喜欢

转载自sillycat.iteye.com/blog/1848592