Skip to content Skip to sidebar Skip to footer

How To Use Both Gps And Network Provider To Get Current Location Latitude And Longitude Values In Android

In my Android application, I want to use both the GPS provider and the network provider for location updates for 5 seconds. First, I would like to use GPS provider (because it giv

Solution 1:

package loca.loca;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;


publicclassLocationActivityextendsActivity {

    double x,y;

    Timer timer;
    LocationManager lm;
    booleangps_enabled=false;
    booleannetwork_enabled=false;

    /** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


            lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);



            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
            network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);



        if (!gps_enabled && !network_enabled) {  Contextcontext= getApplicationContext();
            intduration= Toast.LENGTH_SHORT;
            Toasttoast= Toast.makeText(context, "nothing is enabled", duration);
            toast.show();

        }




        if (gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                    locationListenerGps);
        if (network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                    locationListenerNetwork);
         timer=newTimer();
         timer.schedule(newGetLastLocation(), 20000);

    }

    LocationListenerlocationListenerGps=newLocationListener() {
        publicvoidonLocationChanged(Location location) {
            timer.cancel();
            x =location.getLatitude();
            y = location.getLongitude();
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);

            Contextcontext= getApplicationContext();
            intduration= Toast.LENGTH_SHORT;
            Toasttoast= Toast.makeText(context, "gps enabled "+x + "\n" + y, duration);
            toast.show();
        }

        publicvoidonProviderDisabled(String provider) {
        }

        publicvoidonProviderEnabled(String provider) {
        }

        publicvoidonStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    LocationListenerlocationListenerNetwork=newLocationListener() {
        publicvoidonLocationChanged(Location location) {
            timer.cancel();
            x = location.getLatitude();
            y = location.getLongitude();
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);

            Contextcontext= getApplicationContext();
            intduration= Toast.LENGTH_SHORT;
            Toasttoast= Toast.makeText(context, "network enabled"+x + "\n" + y, duration);
            toast.show();
        }

        publicvoidonProviderDisabled(String provider) {
        }

        publicvoidonProviderEnabled(String provider) {
        }

        publicvoidonStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    classGetLastLocationextendsTimerTask {
        @Overridepublicvoidrun() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest oneif(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                {x = gps_loc.getLatitude();
                y = gps_loc.getLongitude();
                  Contextcontext= getApplicationContext();
                    intduration= Toast.LENGTH_SHORT;
                    Toasttoast= Toast.makeText(context, "gps lastknown "+x + "\n" + y, duration);
                    toast.show();
                }
                 else
                {x = net_loc.getLatitude();
                y = net_loc.getLongitude();
                Contextcontext= getApplicationContext();
                intduration= Toast.LENGTH_SHORT;
                Toasttoast= Toast.makeText(context, "network lastknown "+x + "\n" + y, duration);
                toast.show();

                }

             }

             if(gps_loc!=null){
                  {x = gps_loc.getLatitude();
                y = gps_loc.getLongitude();
                  Contextcontext= getApplicationContext();
                    intduration= Toast.LENGTH_SHORT;
                    Toasttoast= Toast.makeText(context, "gps lastknown "+x + "\n" + y, duration);
                    toast.show();
                  }

             }
             if(net_loc!=null){
                {x = net_loc.getLatitude();
                y = net_loc.getLongitude();
              Contextcontext= getApplicationContext();
              intduration= Toast.LENGTH_SHORT;
              Toasttoast= Toast.makeText(context, "network lastknown "+x + "\n" + y, duration);
                toast.show();

                }
             }
            Contextcontext= getApplicationContext();
            intduration= Toast.LENGTH_SHORT;
            Toasttoast= Toast.makeText(context, "no last know avilable", duration);
            toast.show();

}
}}

Solution 2:

publicclassMyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;`

    publicbooleangetLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabledif(!gps_enabled && !network_enabled)
            returnfalse;
        try{
            if(gps_enabled)
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
            if(network_enabled)
                lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
            timer1=newTimer();
            timer1.schedule(newGetLastLocation(), 30000);
        }catch(Exception x){
            returnfalse;
        }
        returntrue;
    }

    LocationListenerlocationListenerGps=newLocationListener() {
        publicvoidonLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        publicvoidonProviderDisabled(String provider) {}
        publicvoidonProviderEnabled(String provider) {}
        publicvoidonStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListenerlocationListenerNetwork=newLocationListener() {
        publicvoidonLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        publicvoidonProviderDisabled(String provider) {}
        publicvoidonProviderEnabled(String provider) {}
        publicvoidonStatusChanged(String provider, int status, Bundle extras) {}
    };

    classGetLastLocationextendsTimerTask {
        @Overridepublicvoidrun() {
            lm.removeUpdates(locationListenerGps);
            lm.removeUpdates(locationListenerNetwork);

            Location net_loc=null, gps_loc=null;
            if(gps_enabled)
                gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if(network_enabled)
                net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            //if there are both values use the latest oneif(gps_loc!=null && net_loc!=null){
                if(gps_loc.getTime()>net_loc.getTime())
                    locationResult.gotLocation(gps_loc);
                else
                    locationResult.gotLocation(net_loc);
                return;
            }

            if(gps_loc!=null){
                locationResult.gotLocation(gps_loc);
                return;
            }
            if(net_loc!=null){
                locationResult.gotLocation(net_loc);
                return;
            }
            locationResult.gotLocation(null);
        }
    }

    publicstaticabstractclassLocationResult{
        publicabstractvoidgotLocation(Location location);
    }
} 

then use these in your activity:

finalMyLocationmyLocation=newMyLocation();

                HandlermHandler=newHandler(Looper.getMainLooper());
                mHandler.post(newRunnable() {
                    publicvoidrun() {
                        locationResult = newLocationResult(){
                            @OverridepublicvoidgotLocation(final Location location){
                                //Got the location!try{
                                    Methods.savePre(context, ""+location.getLatitude(), "LATITUDE");
                                    Methods.savePre(context, ""+location.getLongitude(), "LONGITUDE");
                                }catch(Exception x){
                                    x.getMessage();
                                }
                                Got_loc= true;
                                //                              String geoAddress  = "geo:" + location.getLatitude() + ","+ location.getLongitude() + "?z=15";//                              Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(geoAddress));//                              context.startActivity(intent);
                            }
                        };
                        myLocation.getLocation(context, locationResult);
                    }
                });
                while(!Got_loc){
                    Thread.sleep(150);
                }

                Loc = Methods.getPref(context, "LATITUDE") + "%%" + Methods.getPref

Solution 3:

The simplest way is to create two different LocationListener and two request location for both gps and network.

Post a Comment for "How To Use Both Gps And Network Provider To Get Current Location Latitude And Longitude Values In Android"