Basic tutorial on Android-10.14 Android GPS

Source: Internet
Author: User

Basic tutorial on Android-10.14 Android GPS
1. Locate related APIs

1) LocationManager

Official API documentation: LocationManager
This is a system service and cannot be new directly. You need:

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

In addition, do not forget to add permissions for GPS positioning:


  

Okay. After obtaining the LocationManager object, we can call the following common methods:

AddGpsStatusListener(GpsStatus. Listener listener): Add a GPS status Listener. AddProximityAlert(Double latitude, double longpolling, float radius, long expiration, PendingIntent intent ):
Add a critical warning GetAllProviders(): Get the list of all locationproviders GetBestProvider(Criteria criteria, boolean enabledOnly): returns the optimal LocationProvider Based on the specified conditions. GetGpsStatus(GpsStatus status): obtains the GPS status. GetLastKnownLocation(String provider): Obtain the last known Location based on LocationProvider GetProvider(String name): Obtain the LocationProvider by name. GetProviders(Boolean enabledOnly): gets all available locationproviders GetProviders(Criteria criteria, boolean enabledOnly): obtains all locationproviders that meet the conditions according to the specified conditions. IsProviderEnabled(String provider): determines whether the specified LocationProvider is available. RemoveGpsStatusListener(GpsStatus. Listener listener): deletes the GPS status Listener. RemoveProximityAlert(PendingIntent intent): deletes a near warning. RequestLocationUpdates(Long minTime, float minDistance, Criteria criteria, PendingIntent intent ):
The location information is periodically obtained through the specified LocationProvider, and corresponding components are started through Intent. RequestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener ):
The location information is periodically obtained through the specified LocationProvider, and the trigger corresponding to the listener is triggered.
2) LocationProvider)

Official API documentation: LocationProvider
This is an abstract representation of the GPS Positioning component. You can call the following method to obtain information about the positioning component!
The common methods are as follows:

GetAccuracy(): Returns the LocationProvider precision. GetName(): Returns the LocationProvider name. GetPowerRequirement(): Obtain power requirements of LocationProvider HasMonetaryCost(): Returns whether the LocationProvider is charged or free. MeetsCriteria(Criteria criteria): determines whether the LocationProvider meets the Criteria of Criteria. RequiresCell(): Determines whether the LocationProvider needs to access the network base station. RequiresNetwork(): Determines whether the LocationProvider needs to access network data. RequiresSatellite(): Determines whether the LocationProvider needs to access the satellite-based positioning system. SupportsAltitude(): Determines whether LocationProvider supports height information. SupportsBearing(): Determines whether LocationProvider supports direction information. SupportsSpeed(): Determines whether LocationProvider supports the speed information.
3) Location)

Official API documentation: Location
Abstract class of location information. We can call the following method to obtain the relevant location information!
The common method is as follows:

Float GetAccuracy(): Double Precision for obtaining positioning information GetAltitude(): Float height for obtaining positioning information GetBearing(): Returns the double direction of the positioning information. GetLatitude(): Returns the latitude double of the positioning information. Getlongpolling(): String precision for obtaining positioning information GetProvider(): Obtain the LocationProvider float that provides the location information. GetSpeed(): The speed at which location information is obtained is boolean. HasAccuracy(): Determines whether the positioning information contains precision information.
4) Criteria (filtering condition)

Official API documentation: Criteria
When obtaining the LocationProvider, you can set the filter condition. This class is used to set the related condition ~
The common method is as follows:

SetAccuracy(Int accuracy): sets the precision requirements. SetAltitudeRequired(Boolean altitudeRequired): sets whether the LocationProvider is required to provide the height information. SetBearingRequired(Boolean bearingRequired): sets whether LocationProvider is required to provide direction information. SetCostAllowed(Boolean costAllowed): sets whether the LocationProvider is required to provide direction information. SetPowerRequirement(Int level): Set the power consumption of the LocationProvider. SetSpeedRequired(Boolean speedRequired): sets whether the LocationProvider is required to provide speed information.
2. Example of obtaining LocationProvider

Run:

As shown in the figure, three available locationproviders are available:

Passive: Passively provided, provided by other programs Gps: Get location information through GPS Network: Obtain location information through the network

Implementation Code:

Layout file:Activity_main.xml:


  
   
   
      
   

MainActivity. java:

Public class MainActivity extends AppCompatActivity implements View. OnClickListener {private Button btn_one; private Button btn_two; private Button btn_three; private TextView TV _result; private LocationManager lm; private List
  
   
PNames = new ArrayList
   
    
(); // The collection that stores the LocationProvider name @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); lm = (LocationManager) getSystemService (Context. LOCATION_SERVICE); bindViews ();} private void bindViews () {btn_one = (Button) findViewById (R. id. btn_one); btn_two = (Button) findViewById (R. id. btn_two); btn_three = (Button) findViewById (R. id. btn_three); TV _result = (TextView) findViewById (R. id. TV _result); btn_one.setOnClickListener (this); btn_two.setOnClickListener (this); btn_three.setOnClickListener (this);} @ Override public void onClick (View v) {switch (v. getId () {case R. id. btn_one: pNames. clear (); pNames = lm. getAllProviders (); TV _result.setText (getProvider (); break; case R. id. btn_two: pNames. clear (); Criteria criteria = new Criteria (); criteria. setCostAllowed (false); // free criteria. setAltitudeRequired (true); // provides the height information criteria. setBearingRequired (true); // provides the direction information pNames = lm. getProviders (criteria, true); TV _result.setText (getProvider (); break; case R. id. btn_three: pNames. clear (); pNames. add (lm. getProvider (LocationManager. GPS_PROVIDER ). getName (); // specify the name TV _result.setText (getProvider (); break ;}// retrieve the array and return the String's method private String getProvider () {StringBuilder sb = new StringBuilder (); for (String s: pNames) {sb. append (s +);} return sb. toString ();}}
   
  
3. Determine whether or not GPS is enabled or not.

The first thing we should do before using GPS positioning is to determine whether GPS is enabled or available. If GPS is not enabled, we need
Turn on GPS to complete positioning! The AGPS is not considered here ~

1) determine whether GPS is available
    private boolean isGpsAble(LocationManager lm){     return lm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)?true:false;    }
2) If GPS is not enabled, turn on the GPS

Method 1: Force turn on GPS, useless after Android 5.0 ....

// Force you to enable private void openGPS (Context context) {Intent gpsIntent = new Intent (); gpsIntent before GPS 5.0. setClassName (com. android. settings, com. android. settings. widget. settingsAppWidgetProvider); gpsIntent. addCategory (android. intent. category. ALTERNATIVE); gpsIntent. setData (Uri. parse (custom: 3); try {PendingIntent. getBroadcast (LocationActivity. this, 0, gpsIntent, 0 ). send ();} catch (PendingIntent. canceledException e) {e. printStackTrace ();}}

Method 2: Go to the GPS location information settings page and allow users to open it on their own.

// Open the location information setting page and ask the user to set private void openGPS2 () {Intent intent = new Intent (Settings. ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult (intent, 0 );}
4. Dynamically Retrieve Location Information

This is very simple. You only need to call the requestLocationUpdates method to set a LocationListener regular detection location!
The sample code is as follows:

Layout:Activity_location.xml:


  
      
   
  

LocationActivity. java:

/*** Created by Jay on 0020. */public class LocationActivity extends AppCompatActivity {private LocationManager lm; private TextView TV _show; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_location); TV _show = (TextView) findViewById (R. id. TV _show); lm = (LocationManager) getSystemService (Context. LOCATION _ SERVICE); if (! IsGpsAble (lm) {Toast. makeText (LocationActivity. this, please turn on GPS ~, Toast. LENGTH_SHORT ). show (); openGPS2 () ;}// obtain the latest Location information from GPS lc = lm. getLastKnownLocation (LocationManager. GPS_PROVIDER); updateShow (lc); // you can call this operation to obtain the GPS location information once every two seconds. requestLocationUpdates (LocationManager. GPS_PROVIDER, 2000, 8, new LocationListener () {@ Override public void onLocationChanged (Location location) {// updateShow (location) when the GPS Location information changes );} @ Override public void onStatusChanged (St Ring provider, int status, Bundle extras) {}@ Override public void onProviderEnabled (String provider) {// When GPS LocationProvider is available, update and locate updateShow (lm. getLastKnownLocation (provider) ;}@ Override public void onProviderDisabled (String provider) {updateShow (null );}});} // define an update display method private void updateShow (Location location) {if (location! = Null) {StringBuilder sb = new StringBuilder (); sb. append (current location information :); sb. append (precision: + location. getlongpolling () +); sb. append (latitude: + location. getLatitude () +); sb. append (Height: + location. getAltitude () +); sb. append (speed: + location. getSpeed () +); sb. append (Direction: + location. getBearing () +); sb. append (positioning accuracy: + location. getAccuracy () +); TV _show.setText (sb. toString ();} else TV _show.setText ();} private Boolean isGpsAble (LocationManager lm) {return lm. isProviderEnabled (android. location. LocationManager. GPS_PROVIDER )? True: false;} // On the Settings page, set private void openGPS2 () {Intent intent = new Intent (Settings. ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult (intent, 0 );}}

Yes, it's very simple. gps needs to be used outdoors, so I took this opportunity to leave a convenience store and bought a cup of milk tea,
Shundao cut ~

RequestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
When the time exceeds minTime (unit: milliseconds), or the position is moved more than minDistance (unit: meters), the method in listener is called to update the GPS information. We recommend that the minTime not be less than 60000, that is, 1 minute. This will be more efficient and power-saving. You need to try your best to join
Update GPS in real time. You can set minTime and minDistance to 0.

By the way, don't forget, you still need a permission:


  
5. Approaching warning (geo-fencing)

Well, it is a fixed point. When the distance between the mobile phone and the point is less than the specified range, the corresponding processing can be triggered!
A little like geo-fencing... We can call the addProximityAlert method of LocationManager to add a nearby warning!
The complete method is as follows:
AddProximityAlert(Double latitude, double longpolling, float radius, long expiration, PendingIntent intent)
Attribute description:

Latitude: Specify the longitude of a fixed point Longpolling: Specify the latitude of a fixed point Radius: Specify the radius Length Expiration: Indicates the number of milliseconds after which the warning will expire.-1 indicates that the warning will never expire. Intent: This parameter specifies the component that triggers the intent when the fixed point is approaching.

The sample code is as follows::

ProximityActivity. java:

/*** Created by Jay on 0021. */public class ProximityActivity extends AppCompatActivity {private LocationManager lm; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_proximity); lm = (LocationManager) getSystemService (Context. LOCATION_SERVICE); // defines the longitude and latitude of a fixed point, double longpolling = 113.56843; double latitude = 22.374937; float radius = 10; // defines the radius, meter Intent intent = new Intent (this, ProximityReceiver. class); PendingIntent pi = PendingIntent. getBroadcast (this,-1, intent, 0); lm. addProximityAlert (latitude, longpolling, radius,-1, pi );}}

You also need to register a broadcast receiver:ProximityReceiver. java:

/*** Created by Jay on 0021. */public class ProximityReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {boolean isEnter = intent. getBooleanExtra (LocationManager. KEY_PROXIMITY_ENTERING, false); if (isEnter) Toast. makeText (context, you have arrived near nansoft B1, Toast. LENGTH_LONG ). show (); else Toast. makeText (context, you have left the vicinity of South soft B1, Toast. LENGTH_LONG ). show ();}}

Don't forget to register:


  

Run:

PS: Okay, set 10 m. As a result, I walked from B1 to D1. It's more than 10 m... It just rained.

 

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.