2009/09/11

Android – Update current location by LocationProvider

摘要

本文將介紹在Android如何使用GPS等LocationProvider取得最新地理位置,並根據此資訊更新地圖物件。

Abstract

This article shows how to get the current geography location from LocationProvider (e.g. GPS) and how to refresh the map object with the location information.



1. Prepare the map resource, Internet accessibility, and location accessibility.

1.1 Open the main.xml file in layout directory, and add a map reource in the file.

Please follow step 1.1 in this article.

1.2 Open AndroidManifest.xml, add the following 4 rules:

<uses-library android:name="com.google.android.maps"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Therefore, the file would be like:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="
http://schemas.android.com/apk/res/android"
package="com.google"
android:versionCode="1"
android:versionName="1.0.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".RideSharing_Car"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="com.google.android.maps"/>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

</manifest>

2. The big picture of program

In the onCreate function, we have to decide choose a specific location provider if there are serveral location providers in your device. The class LocationManager provides accessibility to the system location services. It can access to location functions in all location provider. Do not instantiate this class directly. Instead, you should retrieve it through

Context.getSystemService(Context.LOCATION_SERVICE)

Then, you have to choose one location provider. Call getLocationProvider(…) to set your criteria for choosing a suitable location provider. (Defined in Section 3)

Finally, you should register a listener (locationListener) to be notified periodically by location provider. (Defined in Section 4)

public void requestLocationUpdates (String provider, long minTime, float minDistance, PendingIntent intent)

provider the name of the provider with which to register
minTime the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
minDistance the minimum distance interval for notifications, in meters.
intent a {#link PendingIntet} to be sent for each location update.


onCreate function:

@Override
protected void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
mapView = (MapView)findViewById(R.id.myMapView1);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
strLocationProvider = getLocationProvider(locationManager);
locationManager.requestLocationUpdates(strLocationProvider, 0, 0, locationListener);
}

http://csie-tw.blogspot.com/2009/09/android-update-current-location-by.html

3. getLocationProvider

You can set criteria for choosing a proper location provider. Set some restrictions for criteria ojbect , and then locationManager can get the best provider for to meet the criteria by calling getBestProvider.

If the device only have GPS as the location provider, you may just return LocationManager.GPS_PROVIDER directly.

public String getLocationProvider(LocationManager locationManager)
{
String provider="";
try
{
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
}
catch(Exception e)
{
Log.d(TAG, e.toString());
e.printStackTrace();
}
return provider;
}

4. locationListener

Used for receiving notifications from the LocationManager when the location has changed. These methods are called if the LocationListener has been registered with the location manager service. Whenever the location provider update current location, onLocationChanged(…) will be called. And the location object is available at this moment, so we refresh the map according to the lastest location. Note that the parameter type in animateTo(…) is GeoPoint instead of Location, so call getGeoByLocation before pass the location to this method.

public final LocationListener locationListener = new LocationListener()
{
Override
public void onLocationChanged(Location location)
{

mapView.getController().animateTo(getGeoByLocation(location));
}
@Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
}
};

getGeoByLocation function:

private GeoPoint getGeoByLocation(Location location)
{
GeoPoint gp = null;
try
{
if (location != null)
{
double geoLatitude = location.getLatitude()*1E6;
double geoLongitude = location.getLongitude()*1E6;
gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return gp;
}

References:

[1] LocationManager | Android Developers

Related articles for Android:

[1] Driving Direction (Route Path):

http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html

[2] Enable Android log:

http://csie-tw.blogspot.com/2009/05/enable-android-log-androidlog.html

[3] Setup the Android (Trad. Chinese):

http://csie-tw.blogspot.com/2008/01/androideclipse.html

沒有留言:

2024年React state management趨勢

輕量化 在過去Redux 是 React 狀態管理的首選函式庫。 Redux 提供了強大的功能和靈活性,但也帶來了一定的學習成本和複雜度。 隨著 React 生態的不斷發展,越來越多的開發者開始追求輕量化的狀態管理函式庫。 Zustand 和 Recoil 等庫以其簡單易用、性...