Android gets geo-location information packaged for direct use

Source: Internet
Author: User

 Introduction: Spent a morning study of the following android to obtain latitude and longitude, and then the online reference is assorted, basically is the past few years, and now I use android6.0 reference to other people's results have many mistakes, my heart almost collapsed. Later, constantly Baidu, constantly goole, and constantly find information, and finally solved, and perfect packaging, after direct use on it can be.

1. This class was originally written with Kotlin, and later some things and Java are different, simply change to Java bar, anyway, they are very strong compatibility-----Package class Name: Locationutil

Package Com.example.jason_jan.guangdamiao.util;import Android.content.context;import Android.content.pm.packagemanager;import Android.location.address;import Android.location.geocoder;import Android.location.location;import Android.location.locationlistener;import Android.location.LocationManager; Import Android.os.build;import Android.os.bundle;import Android.support.v4.content.contextcompat;import Android.widget.toast;import Com.example.jason_jan.guangdamiao.globalconstant.logutils;import java.io.IOException ; Import java.util.list;/** * Created by Jason_jan on 2017/7/14.    */public class Locationutil {//latitude public static double latitude = 0.0;    Longitude public static double longitude = 0.0;    public static Locationmanager Locationmanager;    public static location location;    private static String provider; /** * Initialize location information * * @param context */public static void Initlocation (context context) {Locationl Istener Locationlistener = new Locationlistener() {@Override public void onstatuschanged (String arg0, int arg1, Bundle arg2) {//T                ODO auto-generated Method stub} @Override public void onproviderenabled (String arg0) { TODO auto-generated Method stub} @Override public void Onproviderdisabl Ed (String arg0) {//TODO auto-generated method stub} @Override public Vo            ID onlocationchanged (location arg0) {//TODO auto-generated Method Stub//update current latitude and longitude        }        };        Get location Service Locationmanager = (Locationmanager) context.getsystemservice (Context.location_service);        Gets the currently available position controller list<string> List = Locationmanager.getproviders (true); if (List.contains (Locationmanager.gps_provider)) {//is the GPS position controller PROVIDER = Locationmanager.gps_prov        IDER; } else if (list.contains(Locationmanager.network_provider))        {//Is the network location controller Provider = Locationmanager.network_provider;            } else {Toast.maketext (context, "Please check if network or GPS is on", Toast.length_long). Show ();        Return } if (Build.VERSION.SDK_INT >= && contextcompat.checkselfpermission (context, Android . Manifest.permission.ACCESS_FINE_LOCATION)! = packagemanager.permission_granted && contextcompat.ch Eckselfpermission (Context, Android.        Manifest.permission.ACCESS_COARSE_LOCATION)! = packagemanager.permission_granted) {return;        } location = Locationmanager.getlastknownlocation (provider);  if (location = null) {//Gets the current position, this only uses the longitude and latitude String stringposition = "Latitude:" + location.getlatitude () +            ", Longitude is:" + location.getlongitude ();            Longitude=location.getlongitude ();        Latitude=location.getlatitude ();    Toast.maketext (context, stringposition, Toast.length_long). Show (); }//Bind location event, whether the listening position changes//The first parameter is the controller type the second parameter is the time interval in which the listener position changes (in milliseconds)///The third parameter is the interval of the position change (unit: M) The fourth parameter is the position listener Loc        Ationmanager.requestlocationupdates (provider, 2, Locationlistener);            } public static String getaddress (location Location,context Context) throws IOException {if (location==null) {            LogUtils.INSTANCE.d_debugprint ("Error", "Location not Found");        Return "";        } Geocoder Geocoder = new Geocoder (context);        Boolean flag = Geocoder.ispresent ();        LogUtils.INSTANCE.d_debugprint ("Location information", "The flag is" +flag);        StringBuilder StringBuilder = new StringBuilder (); try {//Get geo-location information based on latitude and longitude list<address> addresses = geocoder.getfromlocation (Location.getlatitude (            ), Location.getlongitude (), 1);            LogUtils.INSTANCE.d_debugprint ("Longitude", Double.tostring (Location.getlatitude ())); LogUtils.INSTANCE.d_debugPrint ("Latitude", Double.tostring (Location.getlongitude ()));            Get geo-location information by address//list<address> addresses = Geocoder.getfromlocationname ("No. No. 321, Yan River Road, Zhuhai Xiangzhou District, Guangdong Province", 1);                if (addresses.size () > 0) {Address address = Addresses.get (0); for (int i = 0; i < Address.getmaxaddresslineindex (); i++) {Stringbuilder.append (address.getaddress                Line (i)). Append ("\ n"); } stringbuilder.append (Address.getcountryname ()). Append ("_");//National Stringbuilder.append (addre                Ss.getfeaturename ()). Append ("_");///Peripheral address Stringbuilder.append (Address.getlocality ()). Append ("_");//City                Stringbuilder.append (Address.getpostalcode ()). Append ("_"); Stringbuilder.append (Address.getcountrycode ()). Append ("_");//Country Code stringbuilder.append (Address.getadminarea         ()). Append ("_");//Province Stringbuilder.append (Address.getsubadminarea ()). Append ("_");       Stringbuilder.append (Address.getthoroughfare ()). Append ("_");//Road Stringbuilder.append (address.getsub Locality ()). Append ("_");//Xiangzhou District Stringbuilder.append (Address.getlatitude ()). Append ("_");//Longitude S                Tringbuilder.append (Address.getlongitude ());//Dimension/*system.out.println (Stringbuilder.tostring ()); */            LogUtils.INSTANCE.d_debugprint ("Acquired location:", stringbuilder.tostring ()); }} catch (IOException e) {//TODO auto-generated Catch block Toast.maketext (context, "error",            Toast.length_long). Show ();        E.printstacktrace ();    } return stringbuilder.tostring (); }}

  

2. Simply explain the above code

It is important to-----5 static variables. Locationmanager is the boss. Latitude and longitude is what we need.

-----Initialize the location information, at the time of use, the first initialization is OK.

-----inside a listening position information, no tube, directly copied.

-----is followed by a location service from Locationmanager.

-----The last one is the bind position time, and the listening position is changed.

-----Noteworthy is that there is a version to judge, do not write, there are some version of the TM, and then how how, bored to death, this first plus, the role does not know if there is, but the latter with the time to pay attention to some of the permissions issues, I mentioned in the back.

3. Then there is a static method that getaddress to get the location information we need by longitude and latitude. Copy it directly. But there is a log to print something, just delete it well. This is the thing-----LogUtils.INSTANCE.d_debugprint (). This thing is what I encapsulate to print the stack information on how many rows in which function, and only when debugging is valid. There is time behind me to write this blog.

4. It's easier to call. Note that this is called, because the service is running in the background, to use a thread to find the location of the function, because the main thread is very busy, and crash.

  

  if (Contextcompat.checkselfpermission (this, Manifest.permission.ACCESS_COARSE_LOCATION)! = packagemanager.permission_granted) {  requestpermissions (new  string[]{manifest.permission.access _coarse_location}, Request_permission_location);         Else {            locationutil.initlocation (this);            LogUtils.INSTANCE.d_debugprint ("Longitude:", Double.tostring (locationutil.longitude));            LogUtils.INSTANCE.d_debugprint ("Latitude:", Double.tostring (locationutil.latitude));        }

For the above if, it is very important, I am looking for this in the morning, it is good to solve, but this will still error =====


@TargetApi (build.version_codes. M
@Override
protected void OnCreate (Bundle savedinstancestate)
{。。。 }
Add a @targetapi (build.version_codes. M) so it's okay.

5. Threads, what about threads? Don't worry, ===== down there.
  
 new Thread (NewRunnable () {@Override Public voidrun () {Try{str_location=locationutil.getaddress (Locationutil.location,getapplicationcontext ()); Location information-----A string}Catch(IOException e) {e.printstacktrace (); } handler_location.post (NewRunnable () {@Override Public voidrun () {Toast.maketext (Getapplicationcontext (), Str_location,toast.length_long). Show ();            }                }); }}). Start ();

6. It is very convenient to use it. Note There are also the necessary permissions in =====androidmanifest.xml
<!--get the current location right--    <uses-permission android:name= "Android.permission.ACCESS_FINE_LOCATION"/> <!--only network-located permissions--    <uses-permission android:name= "Android.permission.ACCESS_COARSE_LOCATION"/>< !--Permissions for network access--    <uses-permission android:name= "Android.permission.INTERNET"/>

This thing is also very deceptive. Attention Plus.

7.That ' all. Keep doing it!!!

  

Android gets geo-location information packaged for direct use

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.