How to determine location of device in Android using IP address

前端 未结 5 1784
忘掉有多难
忘掉有多难 2021-02-04 05:21

I am developing an Android app. I want to determine the location of the device using its IP address. Where do I start? The links on Google APIs are not conclusive enough. Thanks

5条回答
  •  粉色の甜心
    2021-02-04 05:49

    You can use freegeoip.net.

    It's a free, open source service. You can use the service directly or run it on your personal server. It can also get deployed to Heroku pretty easily.

    To get the IP location simply use OkHttp to send a http/https request:

    String url = "https://freegeoip.net/json/"
    Request mRequest = new Request.Builder()
            .url(url)
            .build();
    Context mContext // A UI context
    new OkHttpClient().newCall(mRequest).enqueue(new Callback() {
        Handler mainHandler = new Handler(mContext.getApplicationContext().getMainLooper());
    
        @Override
        public void onResponse(Call call, Response response) {
            String responseBody = null;
            try {
                responseBody = response.body().string();
            } catch (final IOException e) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // handle error
                    }
                });
            }
    
            final String finalResponseBody = responseBody;
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    // handle response body
                    try {
                        JSONObject locationObject = new JSONObject(finalResponseBody);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
        @Override
        public void onFailure(Call call, final IOException e) {
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    mNetworkListener.onNetworkError(e.getMessage());
                }
            });
        }
    });
    

    And the response will look like something like this:

    {
        "ip": "192.30.253.113",
        "country_code": "US",
        "country_name": "United States",
        "region_code": "CA",
        "region_name": "California",
        "city": "San Francisco",
        "zip_code": "94107",
        "time_zone": "America/Los_Angeles",
        "latitude": 37.7697,
        "longitude": -122.3933,
        "metro_code": 807
    }
    

提交回复
热议问题