---
title: "Android UI(8)Building Apps with User Info&Location"
author: "sillycat"
date: "2013-04-17T04:44:41Z"
tags: []
categories: ["移动开发"]
slug: "android-ui-8-building-apps-with-user-info-location"
draft: false
lastmod: "2013-04-17T04:44:41Z"
id: 1848592
url: "https://sillycat.iteye.com/blog/1848592"
---

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 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 &gt;= Build.VERSION\_CODES.GINGERBREAD && Geocoder.isPresent(); private class ReverseGeocodingTask extends AsyncTask { 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

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() &gt; 0) { Address address = addresses.get(0); String addressText = String.format( "%s, %s, %s", address.getMaxAddressLineIndex() &gt; 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() -----&gt; 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] --&gt; \[Applications] --&gt; Running Services Context.bindService() bindService ---&gt; onCreate() ---&gt; onBind() Second Time, nothing unbindService ----&gt; onUnbind() ---&gt; 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