How to get current Location(latitude , longitude) while gps is off using FusedLocationApi in android -
i have used latest api. have implement fusedlocationapi , getting current location if gps on. have connected google play services still not getting current location.
i use code:
import android.app.alertdialog; import android.content.context; import android.content.dialoginterface; import android.content.intent; import android.location.location; import android.os.bundle; import android.provider.settings; import com.google.android.gms.common.connectionresult; import com.google.android.gms.common.api.googleapiclient; import com.google.android.gms.common.api.googleapiclient.connectioncallbacks; import com.google.android.gms.common.api.googleapiclient.onconnectionfailedlistener; import com.google.android.gms.location.locationrequest; import com.google.android.gms.location.locationservices; public class gpstracker implements connectioncallbacks, onconnectionfailedlistener, com.google.android.gms.location.locationlistener { private onlocationchangedlistener mlocationchangedlistener; // minimum distance change updates in meters private static final float min_distance_change_for_updates = 0; // 10 meters // minimum time between updates in milliseconds private static final long min_time_bw_updates = 1000 * 60 * 1; // 1 minute public static final long fastest_update_interval_in_milliseconds = min_time_bw_updates / 2; private final context mcontext; // declaring location manager protected locationrequest mlocationrequest; // flag gps status boolean isgpsenabled = false; // flag network status boolean isnetworkenabled = false; // flag gps status boolean cangetlocation = false; // current best location estimate private location mbestreading; private googleapiclient mgoogleapiclient; location mcurrentlocation; // location double latitude; // latitude double longitude; // longitude public void setlocationchangedlistener(onlocationchangedlistener listener) { mlocationchangedlistener = listener; } public gpstracker(context context) { this.mcontext = context; buildgoogleapiclient(); } /** * builds googleapiclient. uses addapi() method request locationservices api. */ protected synchronized void buildgoogleapiclient() { createlocationrequest(); mgoogleapiclient = new googleapiclient.builder(mcontext) .addconnectioncallbacks(this) .addonconnectionfailedlistener(this) .addapi(locationservices.api) .build(); if (mcurrentlocation == null) { mcurrentlocation = locationservices.fusedlocationapi.getlastlocation(mgoogleapiclient); if (mcurrentlocation != null) cangetlocation = true; } mgoogleapiclient.connect(); } protected void createlocationrequest() { mlocationrequest = new locationrequest(); // sets desired interval active location updates. interval // inexact. may not receive updates @ if no location sources available, or // may receive them slower requested. may receive updates faster // requested if other applications requesting location @ faster interval. mlocationrequest.setinterval(min_time_bw_updates); // sets fastest rate active location updates. interval exact, , // application never receive updates faster value. mlocationrequest.setfastestinterval(fastest_update_interval_in_milliseconds); mlocationrequest.setsmallestdisplacement(min_distance_change_for_updates); mlocationrequest.setpriority(locationrequest.priority_high_accuracy); } /** * function latitude */ public double getlatitude() { if (mcurrentlocation != null) { latitude = mcurrentlocation.getlatitude(); } // return latitude return latitude; } /** * function longitude */ public double getlongitude() { if (mcurrentlocation != null) { longitude = mcurrentlocation.getlongitude(); } // return longitude return longitude; } /** * function check gps/wifi enabled * * @return boolean */ public boolean cangetlocation() { return this.cangetlocation; } /** * function show settings alert dialog on pressing settings button * lauch settings options */ public void showsettingsalert() { alertdialog.builder alertdialog = new alertdialog.builder(mcontext); // setting dialog title alertdialog.settitle("gps settings"); // setting dialog message alertdialog.setmessage("gps not enabled. want go settings menu?"); // on pressing settings button alertdialog.setpositivebutton("settings", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int which) { intent intent = new intent(settings.action_location_source_settings); mcontext.startactivity(intent); } }); // on pressing cancel button alertdialog.setnegativebutton("cancel", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int which) { dialog.cancel(); } }); // showing alert message alertdialog.show(); } /** * removes location updates fusedlocationapi. */ protected void stoplocationupdates() { // practice remove location requests when activity in paused or // stopped state. doing helps battery performance , // recommended in applications request frequent location updates. // final argument {@code requestlocationupdates()} locationlistener // (http://developer.android.com/reference/com/google/android/gms/location/locationlistener.html). locationservices.fusedlocationapi.removelocationupdates(mgoogleapiclient, this); } /** * requests location updates fusedlocationapi. */ protected void startlocationupdates() { // final argument {@code requestlocationupdates()} locationlistener // (http://developer.android.com/reference/com/google/android/gms/location/locationlistener.html). locationservices.fusedlocationapi.requestlocationupdates( mgoogleapiclient, mlocationrequest, this); } @override public void onlocationchanged(location mcurrentlocation) { cangetlocation = true; this.mcurrentlocation = mcurrentlocation; mlocationchangedlistener.onreceivelocation(mcurrentlocation, 1); stoplocationupdates(); } @override public void onconnected(bundle bundle) { if (mcurrentlocation == null) { mcurrentlocation = locationservices.fusedlocationapi.getlastlocation(mgoogleapiclient); if (mcurrentlocation != null) { cangetlocation = true; mlocationchangedlistener.onreceivelocation(mcurrentlocation, 1); } } if (mcurrentlocation == null && mgoogleapiclient.isconnected()) { startlocationupdates(); } } @override public void onconnectionsuspended(int i) { mgoogleapiclient.connect(); } @override public void onconnectionfailed(connectionresult connectionresult) { } public interface onlocationchangedlistener { void onreceivelocation(location receivelocation, int resultcode); } }
here code. while gps off onlocationchanged(location location) callback method not called api.
without gps not possible update current lat long. below code working when gps on in case gps able track current lat long in case agps fetching lat long wifi connection or telecom network , work when device have agps hardware.
import android.location.location; import android.os.bundle; import android.support.v7.app.actionbaractivity; import android.util.log; import android.view.view; import android.widget.button; import android.widget.textview; import android.widget.toast; import com.google.android.gms.common.connectionresult; import com.google.android.gms.common.api.googleapiclient; import com.google.android.gms.common.api.googleapiclient.connectioncallbacks; import com.google.android.gms.common.api.googleapiclient.onconnectionfailedlistener; import com.google.android.gms.location.locationlistener; import com.google.android.gms.location.locationrequest; import com.google.android.gms.location.locationservices; import java.text.dateformat; import java.util.date; /** * getting location updates. * * demonstrates how use fused location provider api updates device's * location. fused location provider part of google play services location apis. * * simpler example shows use of google play services fetch last known location * of device, see * https://github.com/googlesamples/android-play-location/tree/master/basiclocation. * * sample uses google play services, not require authentication. sample * uses google play services authentication, see * https://github.com/googlesamples/android-google-accounts/tree/master/quickstart. */ public class mainactivity extends actionbaractivity implements connectioncallbacks, onconnectionfailedlistener, locationlistener { protected static final string tag = "location-updates-sample"; /** * desired interval location updates. inexact. updates may more or less frequent. */ public static final long update_interval_in_milliseconds = 10000; /** * fastest rate active location updates. exact. updates never more frequent * value. */ public static final long fastest_update_interval_in_milliseconds = update_interval_in_milliseconds / 2; // keys storing activity state in bundle. protected final static string requesting_location_updates_key = "requesting-location-updates-key"; protected final static string location_key = "location-key"; protected final static string last_updated_time_string_key = "last-updated-time-string-key"; /** * provides entry point google play services. */ protected googleapiclient mgoogleapiclient; /** * stores parameters requests fusedlocationproviderapi. */ protected locationrequest mlocationrequest; /** * represents geographical location. */ protected location mcurrentlocation; // ui widgets. protected button mstartupdatesbutton; protected button mstopupdatesbutton; protected textview mlastupdatetimetextview; protected textview mlatitudetextview; protected textview mlongitudetextview; /** * tracks status of location updates request. value changes when user presses * start updates , stop updates buttons. */ protected boolean mrequestinglocationupdates; /** * time when location updated represented string. */ protected string mlastupdatetime; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // locate ui widgets. mstartupdatesbutton = (button) findviewbyid(r.id.start_updates_button); mstopupdatesbutton = (button) findviewbyid(r.id.stop_updates_button); mlatitudetextview = (textview) findviewbyid(r.id.latitude_text); mlongitudetextview = (textview) findviewbyid(r.id.longitude_text); mlastupdatetimetextview = (textview) findviewbyid(r.id.last_update_time_text); mrequestinglocationupdates = false; mlastupdatetime = ""; // update values using data stored in bundle. updatevaluesfrombundle(savedinstancestate); // kick off process of building googleapiclient , requesting locationservices // api. buildgoogleapiclient(); //turngpson(); } /** * updates fields based on data stored in bundle. * * @param savedinstancestate activity state saved in bundle. */ private void updatevaluesfrombundle(bundle savedinstancestate) { log.i(tag, "updating values bundle"); if (savedinstancestate != null) { // update value of mrequestinglocationupdates bundle, , make sure // start updates , stop updates buttons correctly enabled or disabled. if (savedinstancestate.keyset().contains(requesting_location_updates_key)) { mrequestinglocationupdates = savedinstancestate.getboolean( requesting_location_updates_key); setbuttonsenabledstate(); } // update value of mcurrentlocation bundle , update ui show // correct latitude , longitude. if (savedinstancestate.keyset().contains(location_key)) { // since location_key found in bundle, can sure mcurrentlocation // not null. mcurrentlocation = savedinstancestate.getparcelable(location_key); } // update value of mlastupdatetime bundle , update ui. if (savedinstancestate.keyset().contains(last_updated_time_string_key)) { mlastupdatetime = savedinstancestate.getstring(last_updated_time_string_key); } updateui(); } } /** * builds googleapiclient. uses {@code #addapi} method request * locationservices api. */ protected synchronized void buildgoogleapiclient() { log.i(tag, "building googleapiclient"); mgoogleapiclient = new googleapiclient.builder(this) .addconnectioncallbacks(this) .addonconnectionfailedlistener(this) .addapi(locationservices.api) .build(); createlocationrequest(); } /** * sets location request. android has 2 location request settings: * {@code access_coarse_location} , {@code access_fine_location}. these settings control * accuracy of current location. sample uses access_fine_location, defined in * androidmanifest.xml. * <p/> * when access_fine_location setting specified, combined fast update * interval (5 seconds), fused location provider api returns location updates * accurate within few feet. * <p/> * these settings appropriate mapping applications show real-time location * updates. */ protected void createlocationrequest() { mlocationrequest = new locationrequest(); // sets desired interval active location updates. interval // inexact. may not receive updates @ if no location sources available, or // may receive them slower requested. may receive updates faster // requested if other applications requesting location @ faster interval. mlocationrequest.setinterval(update_interval_in_milliseconds); // sets fastest rate active location updates. interval exact, , // application never receive updates faster value. mlocationrequest.setfastestinterval(fastest_update_interval_in_milliseconds); mlocationrequest.setpriority(locationrequest.priority_high_accuracy); } /** * handles start updates button , requests start of location updates. nothing if * updates have been requested. */ public void startupdatesbuttonhandler(view view) { if (!mrequestinglocationupdates) { mrequestinglocationupdates = true; setbuttonsenabledstate(); startlocationupdates(); } } /** * handles stop updates button, , requests removal of location updates. nothing if * updates not requested. */ public void stopupdatesbuttonhandler(view view) { if (mrequestinglocationupdates) { mrequestinglocationupdates = false; setbuttonsenabledstate(); stoplocationupdates(); } } /** * requests location updates fusedlocationapi. */ protected void startlocationupdates() { // final argument {@code requestlocationupdates()} locationlistener // (http://developer.android.com/reference/com/google/android/gms/location/locationlistener.html). locationservices.fusedlocationapi.requestlocationupdates( mgoogleapiclient, mlocationrequest, this); } /** * ensures 1 button enabled @ time. start updates button enabled * if user not requesting location updates. stop updates button enabled if * user requesting location updates. */ private void setbuttonsenabledstate() { if (mrequestinglocationupdates) { mstartupdatesbutton.setenabled(false); mstopupdatesbutton.setenabled(true); } else { mstartupdatesbutton.setenabled(true); mstopupdatesbutton.setenabled(false); } } /** * updates latitude, longitude, , last location time in ui. */ private void updateui() { if (mcurrentlocation != null) { mlatitudetextview.settext(string.valueof(mcurrentlocation.getlatitude())); mlongitudetextview.settext(string.valueof(mcurrentlocation.getlongitude())); mlastupdatetimetextview.settext(mlastupdatetime); } } /** * removes location updates fusedlocationapi. */ protected void stoplocationupdates() { // practice remove location requests when activity in paused or // stopped state. doing helps battery performance , // recommended in applications request frequent location updates. // final argument {@code requestlocationupdates()} locationlistener // (http://developer.android.com/reference/com/google/android/gms/location/locationlistener.html). locationservices.fusedlocationapi.removelocationupdates(mgoogleapiclient, this); } @override protected void onstart() { super.onstart(); mgoogleapiclient.connect(); } @override public void onresume() { super.onresume(); // within {@code onpause()}, pause location updates, leave // connection googleapiclient intact. here, resume receiving // location updates if user has requested them. if (mgoogleapiclient.isconnected() && mrequestinglocationupdates) { startlocationupdates(); } } @override protected void onpause() { super.onpause(); // stop location updates save battery, don't disconnect googleapiclient object. if (mgoogleapiclient.isconnected()) { stoplocationupdates(); } } @override protected void onstop() { mgoogleapiclient.disconnect(); super.onstop(); } /** * runs when googleapiclient object connects. */ @override public void onconnected(bundle connectionhint) { log.i(tag, "connected googleapiclient"); // if initial location never requested, use // fusedlocationapi.getlastlocation() it. if requested, store // value in bundle , check in oncreate(). // not request again unless user requests location updates pressing // start updates button. // // because cache value of initial location in bundle, means if // user launches activity, // moves new location, , changes device orientation, original location // displayed activity re-created. if (mcurrentlocation == null) { mcurrentlocation = locationservices.fusedlocationapi.getlastlocation(mgoogleapiclient); mlastupdatetime = dateformat.gettimeinstance().format(new date()); updateui(); } // if user presses start updates button before googleapiclient connects, set // mrequestinglocationupdates true (see startupdatesbuttonhandler()). here, check // value of mrequestinglocationupdates , if true, start location updates. if (mrequestinglocationupdates) { startlocationupdates(); } } /** * callback fires when location changes. */ @override public void onlocationchanged(location location) { mcurrentlocation = location; mlastupdatetime = dateformat.gettimeinstance().format(new date()); updateui(); toast.maketext(this, getresources().getstring(r.string.location_updated_message), toast.length_short).show(); } @override public void onconnectionsuspended(int cause) { // connection google play services lost reason. call connect() // attempt re-establish connection. log.i(tag, "connection suspended"); mgoogleapiclient.connect(); } @override public void onconnectionfailed(connectionresult result) { // refer javadoc connectionresult see error codes might returned in // onconnectionfailed. log.i(tag, "connection failed: connectionresult.geterrorcode() = " + result.geterrorcode()); } /** * stores activity data in bundle. */ public void onsaveinstancestate(bundle savedinstancestate) { savedinstancestate.putboolean(requesting_location_updates_key, mrequestinglocationupdates); savedinstancestate.putparcelable(location_key, mcurrentlocation); savedinstancestate.putstring(last_updated_time_string_key, mlastupdatetime); super.onsaveinstancestate(savedinstancestate); } }
Comments
Post a Comment