I will start from why you should avoid using ACCESS_COARSE_LOCATION directive in your Manifest.xml file.
ACCESS_COARSE_LOCATION allows you to get approximate location of user’s device. It is detected not by GPS, but using different means – wifi hotspots, network triangulation etc.
Actually, it is pretty accurate and it is worth considering to use in case you need detect user’s location up to 500 meters.
The problem is, that you still need to enable High Accuracy setting for Location detection in your device to make this feature work properly. I got reports from users, that on some devices it should be done in order to make this feature work.
Another big problem with this directive is that Google Play excludes a big number of devices in case it is included into Manifest.xml.
I tested app upload with ACCESS_COARSE_LOCATION and without and found, that without it there is more than 6400 devices supported and with – about 300 less. I checked and found many popular devices in exclusion list.
So, in case you don’t need 500 meters radius location, but only Country and City, then avoid using ACCESS_COARSE_LOCATION.
And now I will tell you how to detect location without using build-in methods.
First, I created a simple php script, which is located on my server.
$content_url = 'http://api.hostip.info/get_json.php?position=true&ip='.$_SERVER['REMOTE_ADDR']; $content = file_get_contents($content_url); echo $content;
It does a really simple work – returns json output from www.hostip.info
It looks as following:
{"country_name":"ESTONIA","country_code":"EE","city":"Tallinn","ip":"217.159.174.218","lat":"59.4339","lng":"24.7281"}
And now some Java code for our Android app:
String urlToRssFeed = "http://koshergator.kosherdev.com/location/location_hostip.php"; HttpClient client = new DefaultHttpClient(); StringBuffer sb = null; try { client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(urlToRssFeed)); HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); } catch (IOException e) { //e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block //e.printStackTrace(); } String location_name = ""; if (sb!=null) { String jSon = sb.toString(); jSon=jSon.replaceAll("^\\{","[{"); jSon=jSon.replaceAll("\\}$", "}]"); try { JSONArray jsonArray = new JSONArray(jSon); JSONObject jsonObject = jsonArray.getJSONObject(0); location_name = jsonObject.getString("country_name"); String city = jsonObject.getString("city"); if (!city.contains("Unknown")) location_name = city +", "+ location_name; } catch (Exception e) { Log.e(TAG,e.getMessage()); } }