get Country of the Phone - Android Phone

Android examples for Phone:Phone Registered Operator

Description

get Country of the Phone

Demo Code

/*******************************************************************************
 * Copyright 2013 momock.com/*from   www . ja  v  a2s . co m*/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.telephony.TelephonyManager;

public class Main {
  public static String getCountry(Context context) {
    String country = Locale.getDefault().getCountry();
    String c = null;
    TelephonyManager tm = (TelephonyManager) context
        .getSystemService(Context.TELEPHONY_SERVICE);
    c = tm.getSimCountryIso();
    if (c != null && c.length() == 2)
      country = c;
    c = tm.getNetworkCountryIso();
    if (c != null && c.length() == 2)
      country = c;

    try {
      LocationManager lm = (LocationManager) context
          .getSystemService(Context.LOCATION_SERVICE);
      Criteria criteria = new Criteria();
      String provider = lm.getBestProvider(criteria, false);
      Location loc = lm.getLastKnownLocation(provider);
      if (loc != null) {
        Geocoder gc = new Geocoder(context, Locale.ENGLISH);
        List<Address> addrs = gc.getFromLocation(loc.getLatitude(),
            loc.getLongitude(), 1);
        if (addrs != null && addrs.size() == 1) {
          c = addrs.get(0).getCountryCode();
          if (c != null && c.length() == 2)
            country = c;
        }
      }
    } catch (Exception e) {
      // Logger.error(e);
    }

    country = country.toLowerCase();
    return country;
  }
}

Related Tutorials