5

i am making an android app using geo-location in android. i am using the location manager for getting the geo-location coordinates.

   locationManager.requestLocationUpdates(provider, 0, 0, this);
   Location location = locationManager.getLastKnownLocation(provider);

and using the postDelayed() function for continuously called the getLastKnownLocation() for the geo-location. and set the interval timing 1000 (1 sec). but i get the response after 20 seconds. Can any body explain me why it happens. i am new in android.

Sourbh Gupta
  • 808
  • 7
  • 16

3 Answers3

3

Note that you shouldn't be calling getLastKnownLocation() every second if you have a Location Listener set up (which it looks like you do). Just use the latest values given in the onLocationChanged() callback.

This code works for me, it registers a Location Listener, which updates the lat/lon member variables, and then the Runnable runs with an initial interval of one second, and then every five seconds (5000 milliseconds) and displays the most current location value.

I put in a Toast to make sure that the Runnable is being run every 5 seconds by handler.postDelayed().

Here is the full Activity code:

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity implements LocationListener {

    LocationManager locationManager;
    Handler handler;
    Location location;

    double latitude;
    double longitude;

    TextView lat;
    TextView lon;

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

        handler = new Handler();

        lat = (TextView) findViewById(R.id.latitudeTextView);
        lon = (TextView) findViewById(R.id.longitudeTextView);

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null){
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }

        handler.postDelayed(runLocation, 1000);
    }

    public Runnable runLocation = new Runnable(){
        @Override
        public void run() {
            lat.setText(String.valueOf(latitude));
            lon.setText(String.valueOf(longitude));
            Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();

            MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
        }
    };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

Edit:

As an alternative, you could take out the use of postDelayed(), and just use the onLocationChanged() events.

In the example below, I used both NETWORK_PROVIDER and GPS_PROVIDER.

This is needed in the AndroidManifest.xml:

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

Here is the modified code, which registers the Activity as a Location Listener for both Network location callbacks and GPS location callbacks, with a minimum time interval of one second. Note that events can come in at a greater interval than one second, but with the GPS location enabled, I saw them coming in every second (it was taking longer with only Network location enabled).

public class MainActivity extends ActionBarActivity implements LocationListener {

    LocationManager locationManager;
    Handler handler;
    Location location;

    double latitude;
    double longitude;

    TextView lat;
    TextView lon;

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

        handler = new Handler();

        lat = (TextView) findViewById(R.id.latitudeTextView);
        lon = (TextView) findViewById(R.id.longitudeTextView);

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null){
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }

        //handler.postDelayed(runLocation, 1000);
    }
/*
    public Runnable runLocation = new Runnable(){
        @Override
        public void run() {
            lat.setText(String.valueOf(latitude));
            lon.setText(String.valueOf(longitude));
            Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();

            MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
        }
    };
*/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        lat.setText(String.valueOf(latitude));
        lon.setText(String.valueOf(longitude));
        Toast.makeText(MainActivity.this, "location changed: " + latitude + " " + longitude, Toast.LENGTH_SHORT).show();
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
  • @SourbhGupta Yes, since your main question was about using `postDelayed()`, I included it in the answer. You could also just get rid of the use of `postDelayed()` altogether, and just use the `onLocationChanged()` events. Can you describe what you are trying to accomplish? – Daniel Nugent May 18 '15 at 06:57
  • @SourbhGupta I just updated the answer with an alternate implementation that does not use `postDelayed()`. – Daniel Nugent May 18 '15 at 07:34
  • i was just trying to get the geolocation of the device either it is moving or not in every second using network provider not the gps and thanks buddy for the help. – Sourbh Gupta May 19 '15 at 04:09
  • @sourbhgupta sure, no problem! Let me know if either of those solutions work for you! – Daniel Nugent May 19 '15 at 04:14
  • your modified version responded only once.. but the first is good it responded continuously minimum in every 2 second . – Sourbh Gupta May 20 '15 at 08:12
  • @SourbhGupta That is simply because with the modified version, it will only prompt when the system gives the `onLocationChanged()` event. If you move around, you will see it respond as you are moving. Also, since this is only using Network Location, the amount of hotspots around will affect how often the callback occurs. – Daniel Nugent May 20 '15 at 15:29
1

use google map api v2

example

   public class MapActivity extends FragmentActivity {
protected GoogleMap map;
protected LatLng start;
protected LatLng end;
TextView tvDistance,tvTime;
CameraPosition mCameraPosition;
    //   LatLng currentLocation ;
Context context;
public static boolean loadMapChk = false;
double getlatitute, getlongitute;
String addressGeo;
/**
 * This activity loads a map and then displays the route and pushpins on it.
 */
@Override 
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);
    context = this;

    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {

        getlatitute = bundle.getDouble("getlatitute");
        getlongitute = bundle.getDouble("getlongitute");
        addressGeo = bundle.getString("addressGeo");
    }


    tvDistance = (TextView) findViewById(R.id.tvDistance);
    tvTime = (TextView) findViewById(R.id.tvTime);

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

    map.setMyLocationEnabled(true);
    map.setOnMyLocationChangeListener(myLocationChangeListener);




}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange (Location location) {
       LatLng loc = new LatLng (location.getLatitude(), location.getLongitude());

//  Toast.makeText(getApplicationContext(),"location.getLongitude()>>>>>>>"+location.getLongitude(),Toast.LENGTH_LONG).show();

     //  map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
       Bitmap bitmapicon = BitmapFactory.decodeResource(context.getResources(),
               R.drawable.start_blue);
       map.addMarker(new MarkerOptions().position(
               new LatLng(location.getLatitude(), location.getLongitude())).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(bitmapicon)));

       if (!loadMapChk)
       {       
       map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 12.5f), 4000, null);
       loadMapChk = true;
       }
       start = new LatLng(location.getLatitude(), location.getLongitude());
       end = new LatLng(getlatitute, getlongitute);

       Bitmap bitmapiconEnd = BitmapFactory.decodeResource(context.getResources(),
               R.drawable.end_green);
       map.addMarker(new MarkerOptions().position(
               new LatLng(getlatitute, getlongitute)).title(addressGeo).icon(BitmapDescriptorFactory.fromBitmap(bitmapiconEnd)));

       Routing routing = new Routing(Routing.TravelMode.DRIVING);
       routing.registerListener(routingListener);
       routing.execute(start, end);


    }
};


@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    loadMapChk = false;
}

      public  RoutingListener routingListener = new RoutingListener() {

@Override
public void onRoutingSuccess(PolylineOptions mPolyOptions, Route route) {
      PolylineOptions polyOptions = new PolylineOptions();
        polyOptions.color(Color.CYAN);
        polyOptions.width(8);
        polyOptions.addAll(mPolyOptions.getPoints());
        tvDistance.setText("Distance : "+route.getDistanceText());
        tvTime.setText("Time : "+route.getDurationText());
      //  Toast.makeText(getApplicationContext(), "Distance : "+route.getDistanceText()+" & Time = "+route.getDurationText(),6).show();
        map.addPolyline(polyOptions);

        // Start marker
        MarkerOptions options = new MarkerOptions();


        // End marker
        options = new MarkerOptions();
        options.position(end);
        options.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green));
        map.addMarker(options);     
}

@Override
public void onRoutingStart() {
    // TODO Auto-generated method stub

}

@Override
public void onRoutingFailure() {
    // TODO Auto-generated method stub

}

};

}

AmDroid
  • 131
  • 5
0

Use timer handeller to implement delay.

 Total time= Time delay+ Server response

You might be facing problem because of that

Nischal Hada
  • 3,230
  • 3
  • 27
  • 57