Home | History | Annotate | Download | only in contacts
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
      5  * use this file except in compliance with the License. You may obtain a copy of
      6  * the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
     12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
     13  * License for the specific language governing permissions and limitations under
     14  * the License
     15  */
     16 
     17 package com.android.providers.contacts;
     18 
     19 import android.content.Context;
     20 import android.location.Country;
     21 import android.location.CountryDetector;
     22 import android.location.CountryListener;
     23 import android.os.Looper;
     24 
     25 import java.util.Locale;
     26 
     27 /**
     28  * This class monitors the change of country.
     29  * <p>
     30  * {@link #getCountryIso()} is used to get the ISO 3166-1 two letters country
     31  * code of current country.
     32  */
     33 public class CountryMonitor {
     34     private String mCurrentCountryIso;
     35     private Context mContext;
     36 
     37     public CountryMonitor(Context context) {
     38         mContext = context;
     39     }
     40 
     41     /**
     42      * Get the current country code
     43      *
     44      * @return the ISO 3166-1 two letters country code of current country.
     45      */
     46     public synchronized String getCountryIso() {
     47         if (mCurrentCountryIso == null) {
     48             final CountryDetector countryDetector =
     49                     (CountryDetector) mContext.getSystemService(Context.COUNTRY_DETECTOR);
     50             Country country = null;
     51             if (countryDetector != null) country = countryDetector.detectCountry();
     52 
     53             if (country == null) {
     54                 // Fallback to Locale if there are issues with CountryDetector
     55                 return Locale.getDefault().getCountry();
     56             }
     57 
     58             mCurrentCountryIso = country.getCountryIso();
     59                 countryDetector.addCountryListener(new CountryListener() {
     60                     public void onCountryDetected(Country country) {
     61                         mCurrentCountryIso = country.getCountryIso();
     62                     }
     63                 }, Looper.getMainLooper());
     64         }
     65         return mCurrentCountryIso;
     66     }
     67 }
     68