2016-09-18 115 views
-1

我可以使用設備的SIM卡的位置從設備獲取國家/地區名稱,但對於沒有SIM卡的平板電腦,這不起作用。當連接到互聯網時,如何從設備的IP獲取國家代碼或國家/地區名稱?如何知道設備IP地址的國家名?

回答

0

這取決於你想要的精確程度 - 注意這個技術不是很準確!有各種通過IP地址擊敗地理定位的方式。

但是,有些網站可以使用IP地址進行查詢,它將返回一個couontry。

但是,如果您不想上網查找,則需要轉儲當前列表,將其編碼到查找表中,並將其存儲在程序中。

你不想存儲每個地址 - 有40億個可能的地址 - 但是存儲大範圍。這將大大減少桌子的尺寸。

0

這是您可以在您的項目中使用的Android版GeoIP庫。 它使用在線API從IP地址獲取國家。

https://github.com/seventhmoon/GeoIp-android

下面是關於如何使用它的代碼段:

ApiManager apiManager = new ApiManager(Volley.newRequestQueue(context)); 
    apiManager.getGeoIpInfo(new Response.Listener<GeoIpResponseModel>() { 
     @Override 
     public void onResponse(GeoIpResponseModel response) { 
      //This is how you get the information. 
      //not all attribute are listed 
      String country = response.getCountry(); 
      String city = response.getCity(); 
      String countryCode = resopnse.getCountryCode(); 
      double latitude = response.getLatitude(); 
      double longtidue = response.getLongitude(); 
      String region = response.getRegion(); 
      String timezone = response.getTimezone(); 
      String isp = response.getIsp(); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      String errorMessage = error.toString(); 
     } 
    }); 
+0

感謝MARMOR,我一直在使用仿真器測試此代碼,但結果是空的。 – hawkeye

+0

我用真實設備檢查仍然不工作!顯示空值。 – hawkeye

相關問題