Android --- 58 --- GPS Positioning for beginners, android --- 58 --- gps

Source: Internet
Author: User

Android --- 58 --- GPS Positioning for beginners, android --- 58 --- gps

GPS is short for Global Positioning System.

Android provides a dedicated LocationManager and Location manager for the GPS function. All services and objects related to GPS positioning will be generated by this object.


Obtain the LocationManager instance:
LocationManager lm = (LocationManager) getSystemService (Context. LOCATION_SERVICE)

 

Three core APIs: LocationManager, LocationProvider, and Location

 

LocationManager provides the following methods:

Boolean addGpsStatusListener (GpsStatus. Listener listener): adds a Listener that listens to the GPS status;

Void addProximityAlert (double latitude, double longpolling, float radius, long expiration, PendingIntent intent): Add a near warning;

List getAllProviders (): obtains the List of all locationproviders;
String getBestProvider (Criteria criteria, boolean enabledOnly): returns the optimal LocationProvider object based on the specified conditions;

GpsStatus getGpsStatus (GpsStatus status): obtains the GPS status;

Location getLastKnownLocation (String provider): Obtain the last known Location based on LocationProvider;

LocationProvider getProvider (String name): obtains the LocationProvider Based on the name;

List getProviders (Criteria criteria, boolean enabledOnly): obtains the names of all LocationProvier that meet the conditions according to the specified conditions;
List getProviders (boolean enabledOnly): gets all available locationproviders;
Boolean isProviderEnabled (String provider): determines whether the specified LocationProvider is available;

Void removeGpsStatusListener (GpsStatus. Listener listener): deletes the GPS status Listener;

Void removeProximityAlert (PendingIntent intent): delete a approaching warning;

Void requestLocationUpdates (String provider, long minTime, float minDistance, PendingIntent intent): periodically obtains positioning information through the specified LocationProvider and starts corresponding components through Intent;

Void requestLocationUpdates (String provider, long minTime, float minDistance, LcoationListener listener): periodically obtains location information through the specified LocationProvider and triggers the trigger corresponding to the listener;

 

LocationProvider class

The abstract identifier of the positioning component, which can be used to obtain information about the positioning;

Provides the following common methods:

String getName (): returns the name of the LocationProvider;

Int getAccuracy (): returns the precision of the LocationProvider;

Int getPowerRequirement (): returns the power requirement of the LocationProvider;

Boolean hasMonetaryCost (): returns whether the LocationProvider is charged or not;

Boolean meetsCriteria (Criteria criteria): determines whether the LocationProvider meets the Criteria condition;

Boolean requiresCell (): determines whether the LocationProvider needs to access the network base station;

Boolean requiresNetword (): determines whether the LocationProvider needs network data;

Boolean requiresStatellite (): determines whether the LocationProvider needs to access the satellite positioning system;

Boolean supportsAltitude (): determines whether the LocationProvider supports height information;

Boolean supportsBearing (): determines whether the LocationProvider supports direction information;

Boolean supportsSpeed (): determines whether the LocationProvider supports the speed information;


LocationListener: Location listener, which monitors location changes and device switches and statuses.

 

Location class

An abstract class that represents location information;

The following method is provided to obtain the positioning information:

Float getAccuracy (): obtains the accuracy of positioning information;

Double getAltitude (): obtains the height of the positioning information;

Float getBearing (): gets the direction of the positioning information;

Double getLatitude (): gets the longitude of the positioning information;

Double getLongitude (): gets the latitude of the positioning information;

String getProvider (): gets the LocationProvider that provides the positioning information;

Float getSpeed (): the speed at which location information is obtained;

Boolean hasAccuracy (): determines whether the location information has longitude information;

Boolean hasAltitude (): determines whether the positioning information has a height;

Boolean hasBearing (): determines whether the positioning information has direction information;

Boolean hasSpeed (): determines whether the positioning information has speed information;

 

 

 


LocationListener: Location listener, which monitors location changes and device switches and statuses.

 

Steps:
1. Obtain the system's LocationManager object
2. Use LocationManager to obtain the Location information by specifying the LocationProvider. The Location information is represented by the Location object.
3. Obtain the Location information from the Location object

 

 

The following are examples:

1. Get all available locationproviders:

Layout file:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.allproviderstest.AllProvidersTest" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/providerList" />    <ListView        android:id="@+id/providers"        android:layout_width="fill_parent"        android:layout_height="fill_parent" >    </ListView></LinearLayout>


 

Activity:

 

public class AllProvidersTest extends Activity {ListView providers;LocationManager lm;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_all_providers_test);providers = (ListView) findViewById(R.id.providers);lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);List<String> providerNames = lm.getAllProviders();ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, providerNames);providers.setAdapter(adapter);}}

 


There are two available locationproviders in the simulator:
Passive: expressed by the constant LocationProvider. PASSIVE_PROVIDER
Gps: represented by the constant LocationProvider. GPS_PROVIDER. LocationProvider object for obtaining location information through GPS

There is also a LocationProvider named network, represented by the constant LocationProvider. NETWORK_PROVIDER,
The LocationProvider object that obtains the positioning information through the mobile communication network.

 

 

2. Get the specified LocationProvider by name:

 

For example:

Get the GPS-based LocationProvider:
LocationProvider locProvider = lm. getProvider (LocationManager. GPS_PROVIDER)

 

Obtain the LocationProvider based on Criteria:

 

 

Layout file:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.freeproviderstest.FreeProvidersTest" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/providerList" />    <ListView        android:id="@+id/providers"        android:layout_width="fill_parent"        android:layout_height="fill_parent" /></LinearLayout>


 

Activity:

 

Public class FreeProvidersTest extends Activity {ListView providers; LocationManager lm; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_free_providers_test); providers = (ListView) findViewById (R. id. providers); lm = (LocationManager) getSystemService (Context. LOCATION_SERVICE); // create the filter condition Criteria cri = new for a LocationProvider Criteria (); // The setting requires that the LocationProvider be free of charge. Cri. setCostAllowed (false); // The setting requires that the LocationProvider provide the height information cri. setAltitudeRequired (true); // The LocationProvider is required to provide the direction information cri. setBearingRequired (true); // obtain the name List of LocationProvider for all system composite conditions <String> providerNames = lm. getProviders (cri, false); System. out. println (providerNames. size (); ArrayAdapter <String> adapter = new ArrayAdapter <String> (this, android. r. layout. simple_list_item_1, providerNames); // use ListView to display all available LocationProviderproviders. setAdapter (adapter );}}


 

 

3.
Obtain positioning data:


Send GPS information through the simulator:

After the simulator is started, you can send GPS Positioning Information on the Emulator Control panel of DDMS.

 

Layout file:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.locationtest.LocationTest" >    <EditText        android:id="@+id/show"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:cursorVisible="false"        android:editable="false" /></LinearLayout>


 

Activity:

Public class LocationTest extends Activity {// defines the LocationManager object LocationManager; // defines the EditText component EditText show in the program interface; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_location_test); show = (EditText) findViewById (R. id. show); locManager = (LocationManager) getSystemService (Context. LOCATION_SERVICE); // obtain the nearest Location location = locManager. getLastKnownLocation (LocationManager. GPS_PROVIDER); // use location to obtain the GPS location information locManager every 3 seconds based on the updateView (location) displayed in EditText. requestLocationUpdates (LocationManager. GPS_PROVIDER, 8, new LocationListener () // ① {@ Overridepublic void onLocationChanged (Location location) {// update the location updateView (Location) when the GPS location information changes );} @ Overridepublic void onProviderDisabled (Str Ing provider) {updateView (null) ;}@ Overridepublic void onProviderEnabled (String provider) {// when the GPS LocationProvider is available, update the location updateView (locManager. getLastKnownLocation (provider);} @ Overridepublic void onStatusChanged (String provider, int status, Bundle extras ){}});} // update the public void updateView (Location newLocation) {if (newLocation! = Null) {StringBuilder sb = new StringBuilder (); sb. append ("real-time location information: \ n"); sb. append ("longitude:"); sb. append (newLocation. getlongpolling (); sb. append ("\ n latitude:"); sb. append (newLocation. getLatitude (); sb. append ("\ n Height:"); sb. append (newLocation. getAltitude (); sb. append ("\ n speed:"); sb. append (newLocation. getSpeed (); sb. append ("\ n Direction:"); sb. append (newLocation. getBearing (); show. setText (sb. toString ();} else {// clear EditTextshow if the input Location object is empty. setText ("");}}}



 

 

4.
Approaching warning:
Add a nearby warning via LocationManager. addProximityAlert (double latitude, double longpolling, float radius, long expiration, PendingIntent intent)

Parameters:

Latitude: longitude of a fixed point
Longpolling: Specify the latitude of a fixed point.
Radius: radius Length
Expiration: this parameter specifies the number of milliseconds after which the near warning will expire.
Intent: this parameter specifies the component corresponding to the intent as it approaches the fixed point.


 

Layout file:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.proximitytest.ProximityTest" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" /></LinearLayout>


 

Activity:

 

Public class ProximityTest extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_proximity_test); // locates the service constant String locService = Context. LOCATION_SERVICE; // locate the Service Manager instance LocationManager; // obtain the locationManager instance LocationManager = (locationManager) getSystemService (locService) through the getSystemService method ); // define the approximate longitude and latitude of Zibo, Shandong Province, double longpolling = 117.3; double latitude = 36.5; // define the radius (5 km) float radius = 5000; // define IntentIntent intent = new Intent (this, ProximityAlertReciever. class); // pack Intent into PendingIntentPendingIntent pi = PendingIntent. getBroadcast (this,-1, intent, 0); // Add nearby warning locationManager. addProximityAlert (latitude, longpolling, radius,-1, pi );}}


 

ProximityAlertReciever:

 

Public class ProximityAlertReciever extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {// obtain whether to enter the specified region boolean isEnter = intent. getBooleanExtra (LocationManager. KEY_PROXIMITY_ENTERING, false); if (isEnter) {// display the prompt Toast. makeText (context, "you have entered Tianhe District, Guangzhou", Toast. LENGTH_LONG ). show ();} else {// display the prompt Toast. makeText (context, "you have left Tianhe District, Guangzhou", Toast. LENGTH_LONG ). show ();}}}


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.