检测用户何时进入新国家/地区

时间:2014-04-03 10:28:10

标签: android listener

我需要检测我的应用的用户何时进入新的国家/地区。我希望有一些我可以使用的听众,并考虑检测电话运营商何时更改并在这些情况下快速检查当前国家/地区。

有更好的方法吗?

每次电池塔发生变化时,我都不想触发检查......这不仅仅是在手机清醒时才有效,但它也可能经常发生并且不是理想的

1 个答案:

答案 0 :(得分:0)

添加这些权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

GPSTracker.java

创建GPS跟踪课程
import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;


public class GPSTracker extends Service implements LocationListener {
    private final Activity mActivity;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;
    Location location;
    double latitude;
    double longitude;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
    protected LocationManager locationManager;

    public GPSTracker(Activity mActivity) {
        this.mActivity = mActivity;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mActivity
                    .getSystemService(LOCATION_SERVICE);
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    Log.d("Network", "Network");

                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        updateGPSCoordinates();
                    }
                }

                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                        Log.d("GPS Enabled", "GPS Enabled");

                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            updateGPSCoordinates();
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e("Error : Location",
                    "Impossible to connect to LocationManager", e);
        }

        return location;
    }

    public void updateGPSCoordinates() {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }


    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        return latitude;
    }


    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        return longitude;
    }

    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mActivity);
        alertDialog.setTitle("GPS Settings");
        alertDialog.setMessage("Enable GPS Settings For Accessing Camera");
        alertDialog.setCancelable(false);

        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mActivity.startActivity(intent);
                    }
                });

        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        mActivity.finish();
                    }
                });

        alertDialog.show();
    }

    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {
            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
            try {
                List<Address> addresses = geocoder.getFromLocation(latitude,
                        longitude, 1);
                return addresses;
            } catch (IOException e) {
                Log.e("Error : Geocoder", "Impossible to connect to Geocoder",
                        e);
            }
        }

        return null;
    }

    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        } else {
            return null;
        }
    }

    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;
        }
    }

    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;
        }
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

现在创建一个计时器任务或来自asynchronous task的无限循环,并延迟并检查国家/地区

public class MainActivity extends Activity {

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;
    private static final String COUNTRY_KEY = "country_key";
    private CountDownTimer mTimer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSharedPreferences = getSharedPreferences(
                MainActivity.this.getCallingPackage(), Context.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
        final GPSTracker gpsTracker = new GPSTracker(this);

        mTimer = new CountDownTimer(Long.MAX_VALUE,10 * 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                if (gpsTracker.canGetLocation()) {
                    Geocoder geoCoder = new Geocoder(getBaseContext(),
                            Locale.getDefault());
                    try {
                        List<Address> addresses = geoCoder.getFromLocation(gpsTracker.latitude,
                                gpsTracker.longitude, 1);

                        if (addresses.size() > 0) {
                            String country = addresses.get(0).getCountryName();
                            if(mSharedPreferences.getString(COUNTRY_KEY, null) == null){
                                //This is the first entry
                                mEditor.putString(COUNTRY_KEY, country);
                                mEditor.commit();
                            }else{
                                String savedCountry = mSharedPreferences.getString(COUNTRY_KEY, null);
                                if(!savedCountry.equals(country)){
                                    //Now the country has changed so do your stuff
                                    Toast.makeText(MainActivity.this, "Country Has changed to " + country,
                                            Toast.LENGTH_LONG).show();
                                    //Also save the country to preferences if you want
                                    //mEditor.putString(COUNTRY_KEY, country);
                                    //mEditor.commit();
                                }
                            }
                        }

                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                } else {
                    gpsTracker.showSettingsAlert();
                }
            }

            @Override
            public void onFinish() {}
        };


        mTimer.start();
    }

}