Mobile location in Android Development (record)

Posted by argh2xxx on Thu, 02 Jan 2020 21:50:03 +0100

This blog mainly records how to locate the mobile phone to a certain city. At present, the third-party map parsing API of Baidu map is used here.

Baidu map open platform address: http://lbsyun.baidu.com/index.php?title=androidsdk/guide/key

The steps are as follows:

1. Use the positioning function of Android to get the longitude and latitude value of the current device.

2. Through Baidu map's parsing API, we can get the Json string containing address information.

3. Analyze json through fastjson, get the city and display it on the interface.

The specific implementation is as follows:

1. The code of the location method class LocationUtil.java is as follows:

/**
 * Positioning method class
 */
public class LocationUtil {

    //Baidu map application key
    public static String baiduKey = "TSg776uecpSG4xRHZvttYDe57u5au72q";

    public static String getLocation(Context mContext) {
        String locationProvider;
        //Get geolocation Manager
        LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        //Get all available location providers
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //If it's GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //If it's Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            Toast.makeText(mContext, "No location provider available", Toast.LENGTH_SHORT).show();
            return null;
        }
        //Get Location
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            return null;
        }
        Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location != null) {
            //Longitude and latitude
            return showLocation(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
        }
        return null;
    }

    public static String showLocation(String wd, String jd) {
        String path = "http://api.map.baidu.com/geocoder?output=json&location=" + wd + "," + jd + "&key=" + baiduKey;
        String locationStr = ApiUtils.submitGetData(path);
        Log.e("path-------", locationStr);
        if (!locationStr.equals("")) {
            return locationStr;
        }
        return null;
    }
}

2. The ApiUtils.submitGetData() method obtains API data through get. The implementation code is as follows:

/**
 * Send Get request to server
 * @param strUrlPath:Interface address (with parameters)
 * @return
 */
public static String submitGetData(String strUrlPath){
    String strResult = "";
    try {
        URL url = new URL(strUrlPath);
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
        httpURLConnection.setConnectTimeout(5000);
        httpURLConnection.setReadTimeout(5000);
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setUseCaches(true);
        //Add header header information so that the server can identify which front-end request is coming from
        //Set the type of request body as text type
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("CLIENT-TYPE", "a");
        BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null){
            buffer.append(line);
        }
        strResult = buffer.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return strResult;
}

3. Open an asynchronous task to perform the positioning operation and process the relevant display.

class myLocationAsyncTask extends AsyncTask<Void, Void, Tb_LocationBaseResult> {


    @Override
    protected Tb_LocationBaseResult doInBackground(Void... voids) {
        String result = LocationUtil.getLocation(mContext);
        tb_locationBaseResult = null;
        if (result != null) {
            tb_locationBaseResult = JSON.parseObject(result, Tb_LocationBaseResult.class);
        }
        return tb_locationBaseResult;
    }

    @Override
    protected void onPostExecute(Tb_LocationBaseResult s) {
        if (s != null) {
            String city = s.get_result().get_addressComponent().get_city();
            tvCityLocation.setText("Current city:" + city);
        }
    }
}

Topics: JSON Mobile PHP Android