Positioning of Xamarin.android

Source: Internet
Author: User

First, preface

By opening our application, we can find that more and more applications are using positioning to make our lives more convenient, so this chapter will learn how to develop positioning in Xamarin.

Ii. preparatory work

Because our virtual machine is running locally on the computer, it is naturally impossible to locate it, but we can use the DDMS tool to help us Debug.

The first thing to determine is the directory where your Android SDK is located, and the reader can find it in the following ways:

Tools-"Options

Then the reader opens the Tools folder under the folder and we can see a lot of files with bat results, and when we open the file named Ddms.bat , we will see the following interface:

From here we can manually send GPS location information.

Note: The project also requires the following permissions

Third, the text

1. Monitor changes in GPS location

In this section we will learn how to get the location manager and get a different location provider through the Location manager, all of which will have multiple locations because our phones are not only GPS-based, but can also be positioned according to the base station and network, of course, the accuracy, power consumption are different, This gives us a more flexible way to control, let's Open the MainActivity.cs file for the new project and write the following code in OnCreate :

1         protected Override void OnCreate (Bundle bundle) 2         {3             base. OnCreate (bundle); 4             Setcontentview (Resource.Layout.Main); 5             Locationmanager lm = (Locationmanager) Getsystemservice (locationservice); 6         }

There are a lot of services in Android that are acquired in this way, so the reader must have this habit, rather than just calling a class just like local development, where we need to Getsystemservice Gets the specified name of the service, such as our Location manager, with the location manager, we can get the location provider, monitoring location changes and so on. In order to be able to see the changes very clearly, we will listen to GPS location information changes, and through toast display, first we let mainactivity Implementation Ilocationlistener the method in the interface, and writes the following code in onlocationchanged :

1          Public void onlocationchanged ( location location) 2         {3             String s = String.Format ("{0}   {1}", Location. Longitude, location. Latitude); 4             Toast.maketext (ApplicationContext, S, Toastlength.short). Show (); 5         }

Finally, we need to register it through the location manager, just write the following code at the end of the OnCreate:

1  the this);

The approximate meaning of this method is to track the change of GPS position, and every 5 seconds to refresh, and two times the location of the interval to 500 meters, according to the actual test of the author does not call your method every 5 seconds, but need to meet at the same time, so later readers will find that even if the GPS location changes will not show changes, This is due to the fact that the position of the change is too small.

After we change the GPS position via DDMS, we can see the following prompt:

2. Get the location provider

We already know that there are multiple location providers, but the reality is not all of the providers we can use, some may be closed, some may be open, then we need to know which location providers are available, only through the location provider can be done, the specific code is as follows:

1[Activity (Label ="Locationstudy", Mainlauncher =true, Icon ="@drawable/icon")]2      Public classmainactivity:listactivity3     {4         protected Override voidOnCreate (Bundle bundle)5         {6             Base. OnCreate (bundle);7Locationmanager LM =(Locationmanager) Getsystemservice (locationservice);8ilist<string> list = lm. Getproviders (true);9ListAdapter =Newarrayadapter<string> ( This, Android.Resource.Layout.SimpleListItem1, list);Ten         } One}

After the successful operation, we can see what the current open location provider is, the following is the author virtual:

We can then select a location provider from which to get the Getprovider method of the location provider, in addition to using the above methods can also get the specified location provider, such as the code will get three different location providers:

1             Locationprovider Lpgps = lm. Getprovider (Locationmanager.gpsprovider); 2             Locationprovider lpnet = lm. Getprovider (Locationmanager.networkprovider); 3             Locationprovider LPPSV = lm. Getprovider (Locationmanager.passiveprovider);

The above methods in practice will be more troublesome, so we also introduce another way to get the location provider, it is based on conditions, through our conditions, the Location manager will choose an optimal location manager to us, such as the following code, we will get a location provider that meets this condition:

1Locationmanager LM =(Locationmanager) Getsystemservice (locationservice);2Criteria CRI =NewCriteria ();3             //accuracy4Cri. accuracy =Accuracy.coarse;5             //Energy consumption6Cri. Powerrequirement =Power.low;7             //Altitude Accuracy8Cri. altituderequired =false;9             //direction AccuracyTenCri. Bearingaccuracy =Accuracy.low; One             //whether to spend ACri. costallowed =false; -             //Horizontal Direction Accuracy -Cri. Horizontalaccuracy =Accuracy.low; the             //Speed Accuracy -Cri. Speedaccuracy =Accuracy.low; -             //does it have speed capability ? -Cri. speedrequired =false; +             //Vertical Direction Accuracy -Cri. Verticalaccuracy =Accuracy.low; +              A             //get the best location provider based on conditions atString pidstr = lm. Getbestprovider (CRI,true); -Locationprovider LP = LM. Getprovider (PIDSTR);

With the comments in the code, we are able to take control of the required features and get the corresponding location provider. Location information is not necessary to listen to determine the current location in real time, we can also use the Location Manager's Requestsingleupdate method to achieve only once, of course, this method is still a bit cumbersome, but also need location information update, There is a way to get information directly to the last location update, so you can avoid the location information must be updated again, it is like before your app opens, the previous app has updated location information, then open your app and then do not need to retrieve again, this method's call is as follows:

1             Locationmanager lm = (Locationmanager) Getsystemservice (locationservice); 2             Location LC = LM. Getlastknownlocation (Locationmanager.gpsprovider);

The method obtains the location information of the last GPs, but there is no location update before this, then the returned location information may be wrong, or does not exist.

3. Track location changes

In the first example we took advantage of an interface to receive location updates, but the best way to do this in Android is not, and we can also use broadcast receivers to receive these location updates, and we'll learn how to use that approach to receive location updates. First we need to create a new broadcast receiver:

1 [Broadcastreceiver ()]2      Public classLocationbroadcast:broadcastreceiver3     {4          Public Override voidOnReceive (Context context, Intent Intent)5         {6Location LC =(location) intent. Extras.get (locationmanager.keylocationchanged);7Toast.maketext (context, LC. Longitude +"   "+LC. Latitude, Toastlength.short). Show ();8         }9}

The content is the same as in the first section, with the toast showing the updated location.

requestlocationupdates Another overloaded method to implement the registration of this broadcast receiver, the code is as follows:

 1  locationmanager lm = (Locationmanage R) Getsystemservice (Locationservice);  2  var  tent = new  Intent (this , typeof   (Locationbroadcast));  3  var  ptent = pendingintent.getbroad Cast (this , 0   4  lm. Requestlocationupdates (Locationmanager.gpsprovider, 5000 , 100 , ptent); 

This one of the author is not much to explain, as long as it is in accordance with this tutorial learning should understand what meaning.

4. Imminent warning

This concept is very easy to understand, naturally with GPS positioning, then we can set up a region, when the user enters or leave the area can notify our app, below we will be slightly modified above to achieve near warning, the first is the broadcast receiver:

1 [Broadcastreceiver ()]2      Public classLocationbroadcast:broadcastreceiver3     {4          Public Override voidOnReceive (Context context, Intent Intent)5         {6             if(Intent. Getbooleanextra (Locationmanager.keyproximityentering,true))7             {8Toast.maketext (Context,"entering", Toastlength.short). Show ();9             }Ten             Else One             { AToast.maketext (Context,"exiting", Toastlength.short). Show (); -             } -         } the}

Here we can get the current to leave this area or enter this area through keyproximityentering , the corresponding registration part is also very simple:

1         protected Override voidOnCreate (Bundle bundle)2         {3             Base. OnCreate (bundle);4Locationmanager LM =(Locationmanager) Getsystemservice (locationservice);5             varTent =NewIntent ( This,typeof(Locationbroadcast));6             varPtent = Pendingintent.getbroadcast ( This, -1, Tent,0);7Lm. Addproximityalert (38.422006, -110.084095, 5000F,-1, ptent);8}

The first three parameters of the Addproximityalert are specified in this range, the number one and the second are fixed a point, the third is the radius, the fourth parameter is the timeout time, here the author set to 1 means no timeout, the last of course is our broadcast receiver.

In the next section we will learn how to achieve slidingmenu effects under xamarin.android.

Positioning of Xamarin.android

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.