isProviderEnabled() never getting called android - java

I am writting code for getting current location (latitude and longitude) of my phone. I display a toast whether Network Location service is provided by the phone or not. This toast doesn't show up ever. The other question is, for getting current location using Network_location, will the app use phone's gprs/internet or not?
I have created the instance of this class in the main activity and then get data using Latitude and Longitude variables of this class, in another class which extends broadcast reciever .
public class GpsClass extends Activity{
public static String Latitude="";
public static String Longitude="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() { // anonymous class
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location currentLocation) {
double lat= currentLocation.getLatitude();
Latitude = Double.toString(lat);
double longt= currentLocation.getLongitude();
Longitude = Double.toString(longt);
}
};
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
Toast.makeText(getApplicationContext(), "Network enabled", 0).show();
}
else
Toast.makeText(getApplicationContext(), "Network not enabled", 0).show();
}
}
Is there anything I am doing wrong?
Regards

I think the problem is that you are passing 0 for duration i.e. last parameter of makeText() method.
Try passing Toast.LENGTH_SHORT or Toast.LENGTH_LONG.
if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
Toast.makeText(getApplicationContext(), "Network enabled", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplicationContext(), "Network not enabled", Toast.LENGTH_LONG).show();

This can help you to get answer to your first question.
The answer to your second question is - No, the app will not use phone's gprs/internet for getting location through network provider.

The problem is setting 0 for duration.
This is a sample example:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
currentLocation = new GeoPoint(location.getLatitude(), location.getLongitude());
// Set Toast Here To Diplay location
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//10000 means request update every 10 sec
//10 tell listener that if location change more than 10m then run locationChanged method
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, locationListener);
} else {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, locationListener);
}

Related

Get GPS when Android Intent is Started

I thought this would be super easy - but this is taking waaaay longer than it should.
I'm simply trying to get the GPS coordinates to go to the logcat, that's literally it.
The intent fires fine. The "Intent Fired" message appears every time. The application just refuses to go to the location changed event.
If someone could take a look and let me know where I'm failing, it would be super appreciated.
public class MyReceiver extends IntentService implements LocationListener {
private LocationManager locationManager;
public MyReceiver() {
super("MyReceiver");
}
protected void onHandleIntent(Intent intent) {
Log.i("DebugMe", "Intent Fired");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
public void onLocationChanged(Location location) {
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("DebugMe", lat + " " + lon);
locationManager.removeUpdates(this);
}
public void onProviderDisabled(String provider) {
Log.d("DebugMe ", "Disabled");
}
public void onProviderEnabled(String provider) {
Log.d("DebugMe","Enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("DebugMe","Status");
}
}
Thank you
Well, the location manager works asynchronously, and IntentService is implemented in such a way, that when onHandleIntent(Intent intent) returns, the service stops itself. That means it's destroyed before any location can be provided to your onLocationChanged(location location) method. If you want to use IntentService you need to block the onHandleIntent(Intent intent) method from returning before you have your location, or use a standard Service and execute stopSelf when you obtain a Location object.
public class MyReceiver extends Service implements LocationListener {
private LocationManager locationManager;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent(intent);
return START_NOT_STICKY;
}
protected void onHandleIntent(Intent intent) {
Log.i("DebugMe", "Intent Fired");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
public void onLocationChanged(Location location) {
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("DebugMe", lat + " " + lon);
locationManager.removeUpdates(this);
// this is where you stop the service
stopSelf();
}
public void onProviderDisabled(String provider) {
Log.d("DebugMe ", "Disabled");
}
public void onProviderEnabled(String provider) {
Log.d("DebugMe", "Enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("DebugMe", "Status");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Keep in mind that this implementation won't run in a separate thread as default, as an IntentService would.

Arcgis Map : Get Current Location Error , Not displaying my current location

Hie,
I tried this sample code that one of the person who gave me this in my other question in stack overflow. I tried using this code but when i run the applicationn, it doesnt locate my current device and it doesnt even display a dot of my location .. The code does not give me any red underline errors but i am unable to locate the current location i am at.
What did i miss out? is there anyone who has a sample working source code file that i can download from to get my current device location??
the codes i used is as followed,
This is my MainActivity.class
public class MainActivity extends Activity {
MapView mMapView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMapView = (MapView) findViewById(R.id.mapview);
mMapView.addLayer(new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"));
mMapView = new MapView(this);
LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(Location loc){
}
};
MyLocation mylocation = new MyLocation();
mylocation.getLocation(this, locationResult);
}
This is MyLocation.java
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
public boolean getLocation(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 enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
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 one
if(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);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
You have to write the code for displaying a red dot in the gotLocation method which is currently empty. That is why you are not getting anything displayed on top of the map.

Get MyLocation using GPS - how to implement 'if else' statement?

I am new to android, and reverse-engineering my way into learning java.
Having got as far using the code below, i have a few problems needing to be resolved while customising it to suit my inentions.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: “ +
“Latitud = “ + loc.getLatitude() +
“Longitud = “ + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Disabled”,
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Enabled”,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
The problem is my (android) home screen starts with a checkboxed page showing two choices (checboxes);
GPS On (Enabled)
GPS Off (Disabled)
Now, question is, i have no idea how to write the 'if else' statement/method which could which could help direct the 'On' scenario to the next stage of getting my location, and for directing the 'Off' scenario back to beginning (Home screen).
Where/how in the code do i declare/insert the checkbox code?
Any assistance welcome please.
Thanks
Basic checkbox check:
final CheckBox cbGPS = (CheckBox) findViewById(R.id.checkBox1);
cbGPS.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()) {
// do this if checked
StartGPSMethod();
} else {
// if not checked do this
// do nothing or
EndGPSMethod();
}
}
});

GPS Android - get positioning only once

Is there a way to access the GPS once instead of having a looper that constantly checks for location updates?
In my scenario all I'm interested in is finding the current co-ordinates and not a continuous connection with the GPS satellite. Does anyone have any ideas how this can be done? Thanks in advance.
Dont use the getLastKnownLocation because that could be returning null or old data.
This code Only fetches the location once a button is pressed and not every time. People use to leave the location listener listen in every instance and that kills the battery life so Use the code snippet I have posted by doing lots of research:
// get the text view and buttons from the xml layout
Button button = (Button) findViewById(R.id.btnGetLocation);
final TextView latitude = (TextView) findViewById(R.id.textview4);
final TextView longitude = (TextView) findViewById(R.id.textview5);
final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mlocation = location;
Log.d("Location Changes", location.toString());
latitude.setText(String.valueOf(location.getLatitude()));
longitude.setText(String.valueOf(location.getLongitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Status Changed", String.valueOf(status));
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Provider Enabled", provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Provider Disabled", provider);
}
};
// Now first make a criteria with your requirements
// this is done to save the battery life of the device
// there are various other other criteria you can search for..
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
// Now create a location manager
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// This is the Best And IMPORTANT part
final Looper looper = null;
// Now whenever the button is clicked fetch the location one time
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationManager.requestSingleUpdate(criteria, locationListener, looper);
}
});
First check if the last know location is recent. If not, I believe you must to set up onLocationChanged listener, but once you get your first valid location you can always stop the stream of updates.
Addition
public class Example extends Activity implements LocationListener {
LocationManager mLocationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
// Do something with the recent location fix
// otherwise wait for the update below
}
else {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
mLocationManager.removeUpdates(this);
}
}
// Required functions
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}

Can't get location on application startup

I am trying to develop little application which at startup shows the name of current location in a toast or something. The code I wrote will show a Toast on the display with the location only is I send the coordinates manually from the Emulator Control View from Eclipse.
My question: Is there a way to force somehow this sending of coordinates at the startup, because I want that Toast when the application is loaded? And how can I do it? Thanks.
Here is the code:
public class HomeActivity extends Activity implements LocationListener {
private LocationManager locationManager;
private String welcomeMsg;
private String crtLocationName;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initLocationManager();
}
private void initLocationManager(){
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 5000, this);
}
*/
#Override
public void onLocationChanged(Location location) {
if (location != null) {
try {
crtLocationName = getLocationName(location);
Toast.makeText( getApplicationContext(), crtLocationName, Toast.LENGTH_LONG).show();
} catch (IOException e) {
welcomeMsg = "Location cannot be determined";
crtLocationName = "";
}
// locationManager.removeUpdates(this);
}
}
#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
}
}
As Emulator doesn't have a GPS receiver, the method onLocationChanged will be only invoked when you give some new coordinates through DDMS.
On the real phone, it will not show a Toast instantly; it will wait before it locates the GPS satellite and receive a GPS fix, then it will show the Toast message.

Categories

Resources