I have used following code for getting the location. It is working fine in Android 4.0.4 but not in 4.1.1. Googled a lot but not found any solution.Please help me Thanks in advance.
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocListener = new UserLocationListener(getApplicationContext());
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1, 0, mLocListener);
} else if (mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1, 0, mLocListener);
}
public class UserLocationListener implements LocationListener {
Context mContext;
String mCurrLocation = null;
double latitude, longitude;
String locale;
public String getLocale() {
return locale;
}
public String getmCurrLocation() {
return mCurrLocation;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public UserLocationListener(Context _mContext) {
mContext = _mContext;
}
#Override
public void onLocationChanged(Location location) {
Geocoder gcd = new Geocoder(mContext, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
longitude = location.getLongitude();
latitude = location.getLatitude();
locale = Locale.getDefault().getCountry();
if (addresses.size() > 0) {
mCurrLocation = formatAddress(addresses.get(0));
} else {
Log.e("LocationListener",
"Geocoder backend service not present");
}
} catch (IOException e) {
} catch (NullPointerException e) {
}
}
/**
* Formats the Address to a meaningful String representation
*
* #param address
* #return String
*/
private String formatAddress(Address address) {
String addr = "";
StringBuilder sb = new StringBuilder();
if (address.getAddressLine(0) != null) {
sb.append(address.getAddressLine(0));
} else if (address.getSubThoroughfare() != null) {
sb.append(address.getSubThoroughfare());
} else if (address.getSubThoroughfare() != null) {
sb.append(address.getSubThoroughfare());
} else if (address.getThoroughfare() != null) {
sb.append(address.getThoroughfare());
} else if (address.getSubLocality() != null) {
sb.append(address.getSubLocality() + ",");
} else if (address.getPremises() != null) {
sb.append(address.getPremises() + ",");
} else if (address.getLocality() != null) {
sb.append(address.getLocality() + ",");
} else if (address.getSubAdminArea() != null) {
sb.append(address.getSubAdminArea() + ",");
} else if (address.getAdminArea() != null) {
sb.append(address.getAdminArea() + ",");
} else if (address.getPostalCode() != null) {
sb.append(address.getPostalCode() + ",");
} else if (address.getCountryName() != null)
sb.append(address.getCountryName() + ",");
addr = sb.toString();
return addr;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Related
In my android app I'm retrieving user location for every 3 minutes and somehow I'm doing it in the following way.problems so far I have faced are
Whenever I'm getting location updates I'm getting multiple values at same time
Sometimes I'm getting both GPS and NETWORK provider values at a time.
I need only one value and also it should be either GPS or NETWORK Provider value,How to achieve this.
Here is my Service
public class MyService extends Service {
private static final String TAG = "TESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 180000;
private static final float LOCATION_DISTANCE = 0.0f;
double lati,longi;
String loc_name;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.i(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
Toast.makeText(getApplicationContext(), ""+location.getLatitude()+"==>"+location.getLongitude(), Toast.LENGTH_SHORT).show();
lati = location.getLatitude();
longi = location.getLongitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
lati, longi, 1);
if (addressList != null && addressList.size() > 0) {
{
loc_name = addressList.get(0).getAddressLine(1);
}
AsyncHttpClient client = new AsyncHttpClient();
final RequestParams params = new RequestParams();
params.put("sendingJSON", composeLocation());
Toast.makeText(getApplicationContext(), "" + params, Toast.LENGTH_LONG).show();
client.post("http://192.168.0.120/gpstracker/send_location.php", params, new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
Log.i("Status ==> ", "Sent to server");
}
public void onFailure(int statusCode, Throwable error, String content) {
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
mLastLocation.set(location);
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(MyService.this, "Service Started", Toast.LENGTH_SHORT).show();
Log.i("Service Started", "Started");
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.i(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
public String composeLocation()
{
ArrayList<HashMap<String, String>> locationList = new ArrayList();
HashMap<String, String> map = new HashMap();
String parsed_lati = String.valueOf(lati);
String parsed_longi = String.valueOf(longi);
map.put("e1", "123");
map.put("lati",parsed_lati);
map.put("longi",parsed_longi);
map.put("loc_name",loc_name);
locationList.add(map);
return new GsonBuilder().create().toJson(locationList);
}
}
You should first check before getting location from both. First check if location is available through gps and if not then use network to get location.
Here is a sample class which have methods for checking location.
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public 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(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled) {
if(location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
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(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("Turn on your GPS to find nearby helpers");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You should use Criteria to request location update instead of using Provider:
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationManager.requestSingleUpdate(criteria, listener, null);
That way you can use only one listener and the location value can be from either GPS or NETWORK provider.
I am creating alarmmanager in one of my activities like following
AlarmManager alarmManager=(AlarmManager) MenuItems.this.getSystemService(Context.ALARM_SERVICE);
Intent intent23 = new Intent(MenuItems.this, MyReceiver.class);
PendingIntent pendingIntent23 = PendingIntent.getBroadcast(MenuItems.this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),300000,
pendingIntent);
After this i have following BroadcastReceiver
public class MyReceiver extends WakefulBroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
MyAlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
This broadcast receiver calls my following service
Public class MyAlarmService extends Service
{
private String server_response,data_to_send;
private String server ;
private String setLocation = "/xyz";
private URL url;
public double mLatitude;
private MainActivity main;
private boolean isGpsEnabled = false;
private sendToserver send;
private Context context;
public String vallatlong;
private boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
private Location mLocation;
public MyAlarmService(Context context)
{
this.context = context;
getLocation();
}
public MyAlarmService()
{
}
public double mLongitude;
private LocationManager mLocationManager;
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
main = new MainActivity();
getLocation();
}
public String getLocation()
{
server = getString(R.string.server_add_new);
try {
Log.e("this is getlocation method ", "1");
mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
/*getting status of the gps*/
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
/*getting status of network provider*/
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled) {
Log.e("no provider", "non availability");
} else {
Log.e("this is getlocation method ", "2");
this.canGetLocation = true;
/*getting location from network provider*/
if (isNetworkEnabled) {
// mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
Log.e("this is getlocation method ", "3");
if (mLocationManager != null) {
Log.e("this is getlocation method ", "7");
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
Log.e("this is getlocation method ", "8");
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
long user_id = main.getDefaultsint("user_id", MyAlarmService.this);
String stringLatitude = String.valueOf(mLatitude);
String stringLongitude = String.valueOf(mLongitude);
vallatlong = stringLatitude+stringLongitude;
try {
url = new URL(server+setLocation);
data_to_send = "lat=" + mLatitude + "&";
data_to_send += "long=" + mLongitude + "&";
data_to_send += "user_id=" + user_id ;
Log.e("data to send", "url"+data_to_send);
send = new sendToserver(url, data_to_send);
send.execute();
Log.e("this is getlocation method ", "6");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
/*if gps is enabled then get location using gps*/
if (isGpsEnabled) {
if (mLocation == null) {
// mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
Log.e("this is getlocation method ", "4");
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
Log.e("this is getlocation method ", "5");
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
long user_id = main.getDefaultsint("user_id", MyAlarmService.this);
try {
url = new URL(server+setLocation);
data_to_send = "lat=" + mLatitude + "&";
data_to_send += "long=" + mLongitude + "&";
data_to_send += "user_id=" + user_id ;
Log.e("data to send", "url"+data_to_send);
send = new sendToserver(url, data_to_send);
send.execute();
Log.e("this is getlocation method ", "6");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return vallatlong;
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
public double getLatitude() {
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
public double getLongitude() {
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
}
return mLongitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public class sendToserver extends AsyncTask<URL, String, ArrayList<String>>
{
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
}
String data_to_send = "";
URL url;
public sendToserver(URL u, String data){
this.url = u;
this.data_to_send = data;
}
#Override
protected ArrayList<String> doInBackground(URL... params) {
BufferedReader reader=null;
try
{
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_to_send);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
Log.e("inside", "while loop");
}
server_response = sb.toString();
}
catch(Exception ex)
{
}
return null;
}
}
}
Everything is working fine, my activity sets Alarmmanager which triggers broadcast-receiver after every 5 minutes which executes my service even when my app is closed and phone is not in use i am getting user location at my server, but on some phones like galaxy NoteEdge this code is not working. I am not getting user location after every 5 minutes am i doing something wrong. Please suggest any relevant way of doing this if this is not right way of doing.
I actually wrote the below code on the onclick method of a button,but it is giving null pointer exception,plzz help
public void submit(View v)
{
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double mesg1=location.getLatitude();
double mesg2=location.getLongitude();
}
http://developer.android.com/reference/android/location/LocationManager.html
You should register a listener for location updates - see requestLocationUpdates() method.
Also add ACCESS_FINE_LOCATION permission to your Manifest.
hey follows few steps to get proper and accurate current location.
This way provided you current location both by interent as well as gps.
Step 1.
Put this class in your code.
GetCurLocation.java
public class GetCurLocation implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
public static LocationClient mLocationClient;
LocationRequest mLocationRequest;
public static LocationManager locationmanager;
float accuracy = 500;
Activity context;
boolean getLocRegularly = false;
int interval = 1000;
float Radius;
GoogleMap gmap;
SetOnLocationFoundListner OLF;
public interface SetOnLocationFoundListner {
public void onLocationFound(Location location, boolean getLocRegularly,
GoogleMap gmap);
}
public void RemoveUpdates() {
try {
if (mLocationClient != null)
mLocationClient.removeLocationUpdates(this);
if (locationmanager != null)
locationmanager.removeUpdates(LocUpByLocMgr);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* radius should be in meters
*/
public GetCurLocation(Activity activity, int interval,
boolean getLocRegularly, GoogleMap gmap,
SetOnLocationFoundListner OLF, float Radius) {
this.OLF = OLF;
this.gmap = gmap;
this.context = activity;
this.getLocRegularly = getLocRegularly;
this.interval = interval;
this.Radius = Radius;
if (servicesConnected()) {
mLocationClient = new LocationClient(context, this, this);
mLocationClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(interval);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(interval);
}
locationmanager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
locationmanager.requestLocationUpdates(provider, interval, 0,
LocUpByLocMgr);
}
private boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
(Activity) context, 0);
if (dialog != null) {
}
return false;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location location = mLocationClient.getLastLocation();
Log.e("testing",
location.getLatitude() + "," + location.getLongitude()
+ "," + location.getAccuracy());
if (location.getAccuracy() < Radius) {
OLF.onLocationFound(location, getLocRegularly, gmap);
locationmanager.removeUpdates(LocUpByLocMgr);
} else
mLocationClient.requestLocationUpdates(mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LC", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LC", location.getAccuracy() + " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient.removeLocationUpdates(this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
android.location.LocationListener LocUpByLocMgr = new android.location.LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LM", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LM", location.getAccuracy()
+ " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient
.removeLocationUpdates(GetCurLocation.this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
Step 2.
implement setonlocationfoundlistener in class where you want current location,
and declear one more method in your oncreate and after you will get one location found method and it return location and you can get location.getlatitude and location.getlongitude.
GetCurLocation gcl = new GetCurLocation(activity, 0, true, null, this,
2000);
Step 3. make permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
thats all. thanks
public void loc1(View v)
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
Toast.makeText(getApplicationContext(), "latitude",Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "longitude",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
String longitude = "0.00";
String latitude = "0.00";
}
}
}
}
So I have a piece of code I got from the internet that lets me get the latitude and longitude from the current location. What I want now is to get the location of that place. And yes I did allot of research, and got this code from stack overflow from someone that had the same request as me(below). It probably worked for them, but it doesn't work with me. I used an example latitude and longitude because this code wasn't working. The problem is that the addresses is always null. What am I doing wrong? Why isn't geocoder.getFromLocation working? I tried logging addresses aswel, and I get [] as result.
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(51.977315, 5.921753, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
Log.w("My Current loction address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
}
Create Location Utility Class
public class LocationUtility {
private String currentLatitude = "";
private String currentLongitude = "";
private LocationManager mLocationManager = null;
private final int TEN_SECOND = 0;
private final int TEN_METRES = 1;
private final int TWO_MINUTES = 1000 * 60 * 2; // Better Location
String provider;
public LocationUtility(Activity activity) {
mLocationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
getCurrentLocation();
}
private boolean isGpsOn;
private void getCurrentLocation() {
Location gpsLocation = null;
Location networkLocation = null;
mLocationManager.removeUpdates(listener);
/*
* Criteria criteria = new Criteria();
* criteria.setAccuracy(Criteria.ACCURACY_FINE);
* criteria.setCostAllowed(false);
*
* String bestProviderName = mLocationManager.getBestProvider(criteria,
* true);
*
* if(bestProviderName!=null) Logger.d("bestProvider",
* bestProviderName);
*/
gpsLocation = requestUpdatesFromProvider(LocationManager.GPS_PROVIDER);
networkLocation = requestUpdatesFromProvider(LocationManager.NETWORK_PROVIDER);
isGpsOn = true;
if (gpsLocation != null && networkLocation != null) {
updateLocation(getBetterLocation(gpsLocation, networkLocation));
} else if (gpsLocation != null) {
updateLocation(gpsLocation);
} else if (networkLocation != null) {
updateLocation(networkLocation);
} else {
isGpsOn = false;
}
}
public String getCurrentLatitude() {
return currentLatitude;
}
public String getCurrentLongitude() {
return currentLongitude;
}
private final LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null)
updateLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
if (provider != null)
Logger.d(provider + " provider", "disabled");
}
#Override
public void onProviderEnabled(String provider) {
if (provider != null)
Logger.d(provider + " provider", "enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Logger.d("status", "" + status);
}
};
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
private Location getBetterLocation(Location newLocation,
Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return newLocation;
} else if (newLocation == null) {
// A new location is always better than no location
return currentBestLocation;
}
// Check whether the new location fix is newer or older
long timeDelta = newLocation.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use
// the new location
// because the user has likely moved.
if (isSignificantlyNewer) {
return newLocation;
// If the new location is more than two minutes older, it must be
// worse
} else if (isSignificantlyOlder) {
return currentBestLocation;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (newLocation.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(newLocation.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return newLocation;
} else if (isNewer && !isLessAccurate) {
return newLocation;
} else if (isNewer && !isSignificantlyLessAccurate
&& isFromSameProvider) {
return newLocation;
}
return currentBestLocation;
}
private Location requestUpdatesFromProvider(String provider) {
Location location = null;
if (mLocationManager.isProviderEnabled(provider)) {
mLocationManager.requestLocationUpdates(provider, TEN_SECOND,TEN_METRES, listener);
location = mLocationManager.getLastKnownLocation(provider);
}
return location;
}
private void updateLocation(Location location) {
try {
Logger.d("new Location",location.getLatitude() + " " + location.getLongitude());
currentLatitude = String.valueOf(location.getLatitude());
currentLongitude = String.valueOf(location.getLongitude());
} catch (Exception e) {
// if (e != null)
// e.printStackTrace();
}
}
/**
*
* #return
*/
public boolean isGPSON() {
return isGpsOn;
}
public void removeUpdates() {
if (listener != null) {
try {
mLocationManager.removeUpdates(listener);
} catch (Exception e) {
// if (e != null)
// e.printStackTrace();
}
}
}
}
write this method to get current latitude and longitude
public static String[] getLatAndLong(Activity mContext) {
LocationUtility mLocation = new LocationUtility(mContext);
return new String[] { String.valueOf(mLocation.getCurrentLatitude()),String.valueOf(mLocation.getCurrentLongitude()),String.valueOf(mLocation.isGPSON()) };
}
write this into your main activity where you get location details
try {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(lat, Long, 1);
//String address = addresses.get(0).getAddressLine(0);
//String city = addresses.get(0).getAddressLine(1);
//String newstring = city.replaceAll(",","");
//String country = addresses.get(1).getAddressLine(2);
try {
if (addresses != null && addresses.size() >= 0) {
strCity = addresses.get(0).getLocality();
strCounty = addresses.get(0).getCountryName();
strState = addresses.get(0).getAdminArea();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I am showing place by using pin image on google map in android by calling This Url
This url refresh all the time when zoom-in or zoom-out map.
I am using this code for populating pin on map call url in doInbackground an load in onPostExcution of AsyncTask As-
if(!valueoftotal.equalsIgnoreCase("") && !valueoftotal.equalsIgnoreCase(null))
{
if(Integer.parseInt(valueoftotal) > 0 && Integer.parseInt(valueoftotal) <= 100)
{
OverlayItem oi;
if(myHandler.getParsedData()!=null)
{
arrayList = myHandler.getParsedData();
}
linearbottom2.setClickable(true);
mapOverlays.clear();
//OverlayItem overlayItem,overlayItem1;
overlay.removeAll();
lineartabbar.setBackgroundResource(R.drawable.mapbar);
if( arrayList.size()!=0 && arrayList.size()>1 )
{
for(int i = 0; i < arrayList.size(); i++)
{
String latvalue = arrayList.get(i).getLatitude().toString();
String lonvalue = arrayList.get(i).getLongitude().toString();
GeoPoint point = null;
try
{
point = new GeoPoint((int)(Double.parseDouble(latvalue)*1E6),(int)(Double.parseDouble(lonvalue)*1E6));
}
catch (NumberFormatException e)
{
// TODO: handle exception
}
if(point != null)
{
if(arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
System.out.println("overlayyyyyyyyyyyyy" + overlay + "\toiiiiiiiiii"+oi);
if(overlay!=null)
{
overlay.addItem(oi);
}
}
else if(!arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
if(overlay!=null)
{
System.out.println("2overlayyyyyyyyyyyyy" + overlay + "\toiiiiiiiiii" + oi);
overlay.addItem(oi);
}
}
}
}
mapOverlays.add(overlay);
mapView.invalidate();
}
else if( arrayList.size()!=0 && arrayList.size()==1 )
{
for(int i = 0; i < arrayList.size(); i++)
{
String latvalue = arrayList.get(i).getLatitude().toString();
String lonvalue = arrayList.get(i).getLongitude().toString();
GeoPoint point = null;
try
{
point = new GeoPoint((int)(Double.parseDouble(latvalue)*1E6),(int)(Double.parseDouble(lonvalue)*1E6));
}
catch (NumberFormatException e)
{
// TODO: handle exception
}
if(point != null)
{
if(arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
System.out.println("listing when 1 value is "+arrayList.get(i).getUnitstotal());
overlay.addItem(oi);
mc.animateTo(point);
}
else if(!arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
System.out.println("listing when more value is "+ arrayList.get(i).getUnitstotal());
overlay.addItem(oi);
mc.animateTo(point);
mc.setCenter(point);
mc.setZoom(18);
}
}
}
mapOverlays.add(overlay);
mapView.invalidate();
MapController mcontrller =mapView.getController();
But the problem is when I touch map immediately, it remove all pin and start loading new position. I want to load smoothly get all the position first and then remove.
Please anyone help me ASAP, sorry for my explanation.
public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener
{
private EditText editTextShowLocation;
private Button buttonGetLocation;
private ProgressBar progress;
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
progress = (ProgressBar) findViewById(R.id.progressBar1);
progress.setVisibility(View.GONE);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(this);
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
progress.setVisibility(View.VISIBLE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please enable location providers");
builder.setPositiveButton("OK", this);
builder.setNeutralButton("Cancel", this);
builder.create().show();
progress.setVisibility(View.GONE);
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// This needs to stop getting the location data and save the battery power.
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
progress.setVisibility(View.GONE);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == DialogInterface.BUTTON_NEUTRAL){
editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
}else if (which == DialogInterface.BUTTON_POSITIVE) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
}