Example usage for android.location Geocoder isPresent

List of usage examples for android.location Geocoder isPresent

Introduction

In this page you can find the example usage for android.location Geocoder isPresent.

Prototype

public static boolean isPresent() 

Source Link

Document

Returns true if the Geocoder methods getFromLocation and getFromLocationName are implemented.

Usage

From source file:net.frakbot.FWeather.util.WeatherHelper.java

/**
 * Gets the city name (where available), suffixed with the
 * country code./*from  www.ja  v  a2  s.  c  o m*/
 *
 * @param context The current {@link Context}.
 * @param location The Location to get the name for.
 *
 * @return Returns the city name and country (eg. "London,UK")
 *         if available, null otherwise
 */
public static String getCityName(Context context, Location location) {
    String cityName = null;
    if (Geocoder.isPresent()) {
        Geocoder geocoder = new Geocoder(context);
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        } catch (IOException ignored) {
        }

        if (addresses != null && !addresses.isEmpty()) {
            final Address address = addresses.get(0);
            final String city = address.getLocality();
            if (!TextUtils.isEmpty(city)) {
                // We only set the city name if we actually have it
                // (to avoid the country code avoiding returning null)
                cityName = city + "," + address.getCountryCode();
            }
        }
    }

    String encodedCityName = null;

    try {
        encodedCityName = URLEncoder.encode(cityName, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        FLog.d(context, TAG, "Could not encode city name, assume no city available.");
    } catch (NullPointerException enp) {
        FLog.d(context, TAG, "Could not encode city name, assume no city available.");
    }

    return encodedCityName;
}

From source file:com.example.android.location.LocationActivity.java

/**
 * This sample demonstrates how to incorporate location based services in your app and
 * process location updates.  The app also shows how to convert lat/long coordinates to
 * human-readable addresses.//from  ww w. jav a2 s.  c om
 */
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Restore apps state (if exists) after rotation.
    if (savedInstanceState != null) {
        mUseFine = savedInstanceState.getBoolean(KEY_FINE);
        mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
    } else {
        mUseFine = false;
        mUseBoth = false;
    }
    mLatLng = (TextView) findViewById(R.id.latlng);
    mAddress = (TextView) findViewById(R.id.address);
    // Receive location updates from the fine location provider (gps) only.
    mFineProviderButton = (Button) findViewById(R.id.provider_fine);
    // Receive location updates from both the fine (gps) and coarse (network) location
    // providers.
    mBothProviderButton = (Button) findViewById(R.id.provider_both);

    // The isPresent() helper method is only available on Gingerbread or above.
    mGeocoderAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

    // Handler for updating text fields on the UI like the lat/long and address.
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case UPDATE_ADDRESS:
                mAddress.setText((String) msg.obj);
                break;
            case UPDATE_LATLNG:
                mLatLng.setText((String) msg.obj);
                break;
            }
        }
    };
    // Get a reference to the LocationManager object.
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}

From source file:com.sorin.cloudcog.xivelypull.LocationActivity.java

/**
 * This sample demonstrates how to incorporate location based services in
 * your app and process location updates. The app also shows how to convert
 * lat/long coordinates to human-readable addresses.
 *//* ww w  .j  a v a  2 s .  c  o  m*/
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_coordinates);

    // Restore apps state (if exists) after rotation.
    if (savedInstanceState != null) {
        mUseFine = savedInstanceState.getBoolean(KEY_FINE);
        mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
    } else {
        mUseFine = false;
        mUseBoth = false;
    }
    mLatLng = (TextView) findViewById(R.id.latlng);
    mAddress = (TextView) findViewById(R.id.address);
    // Receive location updates from the fine location provider (gps) only.
    mFineProviderButton = (Button) findViewById(R.id.provider_fine);
    // Receive location updates from both the fine (gps) and coarse
    // (network) location
    // providers.
    mBothProviderButton = (Button) findViewById(R.id.provider_both);

    // The isPresent() helper method is only available on Gingerbread or
    // above.
    mGeocoderAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

    // Handler for updating text fields on the UI like the lat/long and
    // address.
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case UPDATE_ADDRESS:
                mAddress.setText((String) msg.obj);
                break;
            case UPDATE_LATLNG:
                mLatLng.setText((String) msg.obj);
                break;
            }
        }
    };
    // Get a reference to the LocationManager object.
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}

From source file:com.kinvey.samples.citywatch.CityWatch.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Logger.getLogger(HttpTransport.class.getName()).setLevel(LOGGING_LEVEL);

    kinveyClient = ((CityWatchApplication) getApplication()).getClient();

    if (!kinveyClient.user().isUserLoggedIn()) {
        login();//from  w  ww . j  a  v  a2s .co m
    } else {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // Note there is no call to SetContentView(...) here.
        // Check out onTabSelected()-- the selected tab and associated
        // fragment
        // is
        // given
        // android.R.id.content as it's parent view, which *is* the content
        // view. Basically, this approach gives the fragments under the tabs
        // the
        // complete window available to our activity without any unnecessary
        // layout inflation.
        setUpTabs();

        curEntity = new CityWatchEntity();
        nearbyAddress = new ArrayList<Address>();
        nearbyEntities = new ArrayList<CityWatchEntity>();

        locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 100, this);

        if (Geocoder.isPresent()) {
            geocoder = new Geocoder(this);
        }

        // get last known location for a quick, rough start. Try GPS, if
        // that
        // fails, try network. If that fails wait for fresh data
        lastKnown = locationmanager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnown == null) {
            lastKnown = locationmanager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        if (lastKnown == null) {
            // if the device has never known it's location, start at 0...?
            lastKnown = new Location(TAG);
            lastKnown.setLatitude(0.0);
            lastKnown.setLongitude(0.0);
        }
        Log.i(TAG, "lastKnown -> " + lastKnown.getLatitude() + ", " + lastKnown.getLongitude());
        setLocationInEntity(lastKnown);
    }

}

From source file:com.uproot.trackme.LocationActivity.java

/**
 * This sample demonstrates how to incorporate location based services in your
 * app and process location updates. The app also shows how to convert
 * lat/long coordinates to human-readable addresses.
 *//*from  ww w  .  j a  v  a 2s.  co  m*/
@SuppressLint({ "NewApi", "HandlerLeak" })
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // clearDB();
    initDatabase();

    Button btn1 = (Button) findViewById(R.id.btn1);
    btn1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
        }
    });

    if (savedInstanceState != null) {
        mUseFine = savedInstanceState.getBoolean(KEY_FINE);
        mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
    } else {
        mUseFine = false;
        mUseBoth = false;
    }
    mUseFine = false;
    mUseBoth = true;
    mLatLng = (TextView) findViewById(R.id.latlng);
    mAddress = (TextView) findViewById(R.id.address);

    // The isPresent() helper method is only available on Gingerbread or
    // above.
    mGeocoderAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

    // Handler for updating text fields on the UI like the lat/long and
    // address.
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case UPDATE_ADDRESS:
                mAddress.setText((String) msg.obj);
                break;
            case UPDATE_LATLNG:
                mLatLng.setText((String) msg.obj);
                break;
            }
        }
    };
    // Get a reference to the LocationManager object.
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    setup();

    myTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            getLocs();
        }
    }, 0, setF * 1000);

}

From source file:com.cloudbees.gasp.activity.GaspLocationsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_locations);

    GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    LocationManager locationManager;//from w  ww  .ja va2s  .co  m
    String svcName = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) getSystemService(svcName);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setSpeedRequired(false);
    criteria.setCostAllowed(true);
    String provider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(provider);
    Log.i(TAG, "CURRENT LOCATION");
    Log.i(TAG, "Latitude = " + location.getLatitude());
    Log.i(TAG, "Longitude = " + location.getLongitude());

    if (location != null) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        Geocoder gc = new Geocoder(this, Locale.getDefault());

        if (!Geocoder.isPresent())
            Log.i(TAG, "No geocoder available");
        else {
            try {
                List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
                StringBuilder sb = new StringBuilder();
                if (addresses.size() > 0) {
                    Address address = addresses.get(0);

                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                        sb.append(address.getAddressLine(i)).append(" ");

                    sb.append(address.getLocality()).append("");
                    sb.append(address.getPostalCode()).append(" ");
                    sb.append(address.getCountryName());
                }
                Log.i(TAG, "Address: " + sb.toString());
            } catch (IOException e) {
                Log.d(TAG, "IOException getting address from geocoder", e);
            }
        }
    }

    map.setMyLocationEnabled(true);

    LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude());
    CameraPosition cameraPosition = new CameraPosition.Builder().target(myLocation).zoom(16).bearing(0).tilt(0)
            .build();
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    new LocationMapper().execute();
}

From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java

/**
 * This sample demonstrates how to incorporate location based services in your app and
 * process location updates.  The app also shows how to convert lat/long coordinates to
 * human-readable addresses./* w w w .j  a v a 2s . c  o  m*/
 */
//@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.geolocation);

    // Restore apps state (if exists) after rotation.
    if (savedInstanceState != null) {
        mUseFine = savedInstanceState.getBoolean(KEY_FINE);
        mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
    } else {
        mUseFine = false;
        mUseBoth = false;
    }
    TextView tv1 = (TextView) findViewById(R.id.textView1);
    TextView tv2 = (TextView) findViewById(R.id.textView2);
    TextView tv3 = (TextView) findViewById(R.id.fileLocation);
    ImageView iv1 = (ImageView) findViewById(R.id.imageView1);
    btnUpload = (Button) findViewById(R.id.btnUpload);
    tv1.setText("Name : " + Session.name);
    tv2.setText("Caption :" + Session.caption);
    iv1.setImageBitmap(Session.image);
    tv3.setVisibility(View.GONE);
    //tv3.setText(Session.fileLocation2);
    mLatLng = (TextView) findViewById(R.id.latlng);
    mAddress = (TextView) findViewById(R.id.address);
    // Receive location updates from the fine location provider (gps) only.
    mFineProviderButton = (Button) findViewById(R.id.provider_fine);
    // Receive location updates from both the fine (gps) and coarse (network) location
    // providers.
    mBothProviderButton = (Button) findViewById(R.id.provider_both);

    // The isPresent() helper method is only available on Gingerbread or above.
    mGeocoderAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

    // Handler for updating text fields on the UI like the lat/long and address.
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case UPDATE_ADDRESS:
                mAddress.setText((String) msg.obj);
                break;
            case UPDATE_LATLNG:
                mLatLng.setText((String) msg.obj);
                String[] res = ((String) msg.obj).split(",");
                lat = res[0];
                longt = res[1];
                break;
            }
        }
    };
    // Get a reference to the LocationManager object.
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mBothProviderButton.performClick();
    btnUpload.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                executeMultipartPost();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}

From source file:com.example.android.location.BaselineActivity.java

/**
 * This sample demonstrates how to incorporate location based services in your app and
 * process location updates.  The app also shows how to convert lat/long coordinates to
 * human-readable addresses./*from   www  . j a v a 2  s  .c  o m*/
 */
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    fileOpen = false;
    // Restore apps state (if exists) after rotation.
    if (savedInstanceState != null) {
        mUseFine = savedInstanceState.getBoolean(KEY_FINE);
        mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
    } else {
        mUseFine = false;
        mUseBoth = false;
    }
    amanager = (AudioManager) getSystemService(AUDIO_SERVICE);

    tb = (ToggleButton) this.findViewById(R.id.tglSetStatus);

    tb.setChecked(fileOpen);
    mLatLng = (TextView) findViewById(R.id.latlng);
    mAddress = (TextView) findViewById(R.id.address);
    mSpeed = (TextView) findViewById(R.id.speed);
    avgSpeedView = (TextView) findViewById(R.id.avgspeedfield);
    avgPaceView = (TextView) findViewById(R.id.avgpacefield);
    mMinPace = (TextView) findViewById(R.id.minpaceIndicator);
    mMaxPace = (TextView) findViewById(R.id.maxpaceIndicator);
    mMaxPace.setText("0.0");
    mMinPace.setText("40.0");
    totalSpeeds = 0;
    measureCount = 0;
    averageSpeed = 0;

    logStartButton = (Button) findViewById(R.id.logStartButton);
    logStartButton.setOnClickListener(new StartButtonListener());

    logStopButton = (Button) findViewById(R.id.logStopButton);
    logStopButton.setOnClickListener(new StopButtonListener());

    // Receive location updates from the fine location provider (gps) only.
    mFineProviderButton = (Button) findViewById(R.id.provider_fine);
    // Receive location updates from both the fine (gps) and coarse (network) location
    // providers.
    mBothProviderButton = (Button) findViewById(R.id.provider_both);

    // The isPresent() helper method is only available on Gingerbread or above.
    mGeocoderAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

    // Handler for updating text fields on the UI like the lat/long and address.
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case UPDATE_ADDRESS:
                mAddress.setText((String) msg.obj);
                break;
            case UPDATE_LATLNG:
                mLatLng.setText((String) msg.obj);
                break;
            case UPDATE_SPEED:
                mSpeed.setText((String) msg.obj);
                break;
            case UPDATE_AVG_SPEED:
                avgSpeedView.setText((String) msg.obj);
                break;
            case UPDATE_AVG_PACE:
                avgPaceView.setText((String) msg.obj);
                break;
            }
        }
    };
    // Get a reference to the LocationManager object.
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    cal = Calendar.getInstance();
    seconds = (int) (cal.getTimeInMillis() / 1000);
    speedBuffer = new ArrayList<Double>();
    speedBuffer.add(0.0);
    speedBuffer.add(0.0);
    speedBuffer.add(0.0);
    gotInfinity = false;
}

From source file:com.happyhours.activity.MyLocationDemoActivity.java

@Override
public void onMarkerDragEnd(Marker arg0) {
    mMessageView.setText("Location = " + arg0.getPosition());

    latitude = "" + arg0.getPosition().latitude;
    longitude = "" + arg0.getPosition().longitude;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent()) {

        (new GetAddressTask(context)).execute(arg0.getPosition());
    }/*  w ww . j av a 2s.  c  o  m*/

}

From source file:de.j4velin.wifiAutoOff.Locations.java

@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if (requestCode == REQUEST_LOCATION) {
        if (resultCode == RESULT_OK) {
            LatLng location = data.getParcelableExtra("location");
            String locationName = "UNKNOWN";
            if (Geocoder.isPresent()) {
                Geocoder gc = new Geocoder(this);
                try {
                    List<Address> result = gc.getFromLocation(location.latitude, location.longitude, 1);
                    if (result != null && !result.isEmpty()) {
                        Address address = result.get(0);
                        locationName = address.getAddressLine(0);
                        if (address.getLocality() != null) {
                            locationName += ", " + address.getLocality();
                        }/*  w  w  w.  jav  a  2 s  . c o m*/
                    }
                } catch (IOException e) {
                    if (BuildConfig.DEBUG)
                        Logger.log(e);
                    e.printStackTrace();
                }
            }
            Database db = Database.getInstance(this);
            db.addLocation(locationName, location);
            db.close();
            locations.add(new Location(locationName, location));
            mAdapter.notifyDataSetChanged();
        }
    } else if (requestCode == REQUEST_BUY) {
        if (resultCode == RESULT_OK) {
            if (data.getIntExtra("RESPONSE_CODE", 0) == 0) {
                try {
                    JSONObject jo = new JSONObject(data.getStringExtra("INAPP_PURCHASE_DATA"));
                    PREMIUM_ENABLED = jo.getString("productId").equals("de.j4velin.wifiautomatic.billing.pro")
                            && jo.getString("developerPayload").equals(getPackageName());
                    getSharedPreferences("settings", Context.MODE_PRIVATE).edit()
                            .putBoolean("pro", PREMIUM_ENABLED).commit();
                    if (PREMIUM_ENABLED) {
                        Toast.makeText(this, "Thank you!", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    if (BuildConfig.DEBUG)
                        Logger.log(e);
                    Toast.makeText(this, e.getClass().getName() + ": " + e.getMessage(), Toast.LENGTH_LONG)
                            .show();
                }
            }
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}