grab the lat and lng - android

So i found this script to get the best location and have added it to a app. When i call for the location it just gives a random number after the package name (com.android.package.currentactivity$1#randomcode)
MyLocation myLocation = new MyLocation();
private void locationClick() {
myLocation.getLocation(this, locationResult));
}
public LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(final Location location){
//Got the location!
});
}
};
and the MyLocation.java
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
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);
}
}
What im trying to get is the lat and lng so i can use is in my activity.

You will need to be more explicit on where do you get that string, so we can help you pinpoint the issue, but that string represent your Activity instance as a String.
public String toString ()
Since: API Level 1
Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
getClass().getName() + '#' + Integer.toHexString(hashCode())
See Writing a useful toString method if you intend implementing your own toString method.
Returns a printable representation of this object.
Edit: It's not your activity, but an inner class inside it (this is told by the $1 part). Perhaps the MyLocation instance?

You need to add one or both of these to your manifest.xml:
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
This is the bulk of my location code. Use it. It works.:
/**************************************************************************
* helper functions for starting/stopping monitoring of Location changes below
**************************************************************************/
public void startListening() {
if (networkLocationListener == null && gpsLocationListener == null) {
// make new listeners
networkLocationListener = new BegetLocationListener(LocationManager.NETWORK_PROVIDER);
gpsLocationListener = new BegetLocationListener(LocationManager.GPS_PROVIDER);
// request very rapid updates initially. after first update, we'll put them back down to a much lower frequency
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 200, networkLocationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 200, gpsLocationListener);
}
Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (networkLocation != null) {
appModel.setLocation(networkLocation);
}
updateDistances(appModel.getLocation());
}
private void stopListening() {
if (networkLocationListener != null)
locationManager.removeUpdates(networkLocationListener);
if (gpsLocationListener != null)
locationManager.removeUpdates(gpsLocationListener);
gpsLocationListener = null;
networkLocationListener = null;
}
private void handleListenerDisabled(BegetLocationListener listener) {
if (!appModel.getFlags().hasLocationMessageBeenDisplayed()) {
if (networkLocationListener.locationStatusKnown && gpsLocationListener.locationStatusKnown) {
if (networkLocationListener.locationIsEnabled && !gpsLocationListener.locationIsEnabled) {
showAlert(YES_NETWORK_NO_GPS_MSG, BaseActivity.DIALOG_LOCATION);
appModel.getFlags().setLocationMessageDisplayed(true);
} else {
showAlert(NO_NETWORK_NO_GPS_MSG, BaseActivity.DIALOG_LOCATION);
appModel.getFlags().setLocationMessageDisplayed(true);
}
}
}
}
private void handleLocationChanged(Location location) {
if (location == null) {
return;
}
if (isBetterLocation(location, appModel.getLocation())) {
appModel.setLocation(location);
stopListening();
}
}
private class BegetLocationListener implements LocationListener {
private String provider = "";
private boolean locationIsEnabled = true;
private boolean locationStatusKnown = true;
public BegetLocationListener(String provider) {
this.provider = provider;
}
#Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
handleLocationChanged(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
startListening();
}
public void onProviderDisabled(String provider) {
locationStatusKnown = true;
locationIsEnabled = false;
handleListenerDisabled(this);
}
}
Obviously you'll want to remove the appModel stuff and the custom dialog stuff.

Related

GPS/Network Location of SQLite entry

Hello I have a question for a class project app I am working on. I have a Notes app that pretty simply records text input from edit texts into a SQLite database and then retrieves each of them to a list fragment for the user to view. They can also click on each list item and that opens another fragment that displays the "details" of the entry, i.e. Subject, body content, time, and date entered. I want to make an addition that records user's current GPS/Network location for that particular entry (geotagging). I have a floating action button in the note details fragment that should link to a Map fragment with a marker on it corresponding to the location recorded when that entry was made. I'm fairly new to Android so still learning about all this. Just a bit hung up on this. Does anyone have a good explanation on how to save location into that same database (lat, long) when the entry is submitted, and then when the user clicks the FAB in details fragment, it displays a map with location marker for each respective entry? Please let me know if anyone can help, or if any of my database classes are needed?
Also want to add that I have indeed looked in quite a few places on Google, but I'm not quite sure if maybe I am using the wrong terminology or what, but results seems to be off for what I am looking for.
Here you have a class for getting the location:
public class MyLocation {
private static final int REQUEST_PERMISSIONS = 1;
private Timer timer1;
private LocationManager lm;
private LocationResult locationResult;
private boolean gps_enabled = false;
private boolean network_enabled = false;
private String[] permissions = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
};
public boolean getLocation(final 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;
try {
boolean allPermissionsGranted = true;
for(int i=0; i<permissions.length;i++) {
if(!Utils.PermissionGranted(permissions[i], context)) allPermissionsGranted = false;
}
if(!allPermissionsGranted) {
ActivityCompat.requestPermissions((Activity)context, permissions, REQUEST_PERMISSIONS);
return false;
}
if (gps_enabled) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
});
}
if (network_enabled) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
});
}
} catch (SecurityException e) {
Utils.Toast(context, e.getMessage());
}
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 5000);
return true;
}
private 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) {}
};
private 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) {}
};
private 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);
}
}
When you are about to add a new note just do:
MyLocation.LocationResult locationResult = new MyLocation.LocationResult(){
#Override
public void gotLocation(Location location){
mCurrentLocation = location;
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Any UI related code
}
});
}
};
Then for the map:
Go to https://developer.android.com/training/maps/index.html. You have to add a marker for every location in your database.

Unable to get location from GPS?

I am trying to get the location from the GPS but not able to get it. this is because the location is accessed by the Network provider.
If I am commenting all the code of network provider then the GPS location returns null.
I have tried so much, but unable to resolve this.
If anybody can help then it will be great help for me.
I am using this link for the reference..
https://stackoverflow.com/a/3145655/1395259
Here is my code:
MainActivity.java
package com.example.locationsimple;
import com.example.locationsimple.MyLocation.LocationResult;
import android.location.Location;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textView;
LocationResult locationResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textViewLocation);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationResult = new LocationResult(){
#Override
public void gotLocation(Location location) {
while(true)
{
Log.i("Log", "Inside while loop ");
if(location != null)
{
Log.i("Log", "Here the location is not null");
if(location.getLatitude() !=0.0 || location.getLongitude() != 0.0)
{
if(location.getAccuracy() < 100)
{
Log.i("Log", "Inside while loop BREAKS");
try
{
String loc = "Lattitude: "+location.getLatitude()+" longi "+location.getLongitude()+" Accur "+location.getAccuracy()+" Time "+location.getTime();
Log.i("Log",loc);
Toast.makeText(MainActivity.this, ""+loc, Toast.LENGTH_LONG).show();
textView.setText(loc);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
break;
}
else
{
Log.i("Log", "no Accuracy");
Log.i("Log", "latti"+location.getLatitude()+" Longi "+location.getLongitude()+" Accur "+location.getAccuracy()+location.getProvider());
break;
}
}
}
else
{
Log.i("Log", "Here got the location is null");
break;
}
}
//textView.setText(location.getLatitude()+"::"+location.getLongitude()+"::"+location.getAccuracy()+" Provider "+location.getProvider());
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(MainActivity.this, locationResult);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyLocation.java
package com.example.locationsimple;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
Context mContext;
public boolean getLocation(Context context, LocationResult result)
{
mContext = context;
//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);
/*Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_HIGH);
lm.getBestProvider(criteria, true);*/
//exceptions will be thrown if provider is not permitted.
try
{
gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex)
{
ex.printStackTrace();
}
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)
{
showSettingsAlert();
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(), 30000);
return true;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle("GPS Is Not Enabled");
// Setting Dialog Message
alertDialog.setMessage("Please Enabled Wireless Network And GPS");
// On pressing Settings button
alertDialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// Showing Alert Message
alertDialog.show();
}
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;
Location 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);
}
}
Thanks..
You can use the below service for getting gps.just invoke this service at the begining.
public class MyService extends Service {
LocationManager locationManager;
#Override
public void onCreate() {
//
// TODO Auto-generated method stub
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
/** Criteria for selecting best provider */
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
/** Passing criteria and select only enabled provider */
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
/** calls the Location Listner */
locationManager.requestLocationUpdates(provider, 500, 0,locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location)
{
System.out.println("+++++++++++++++++++SASI+++++++++++++++++++++++++++++++++++++++++");
String latLongString, addressString = null;
double lat = 0, lng = 0;
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
//latLongString = "Lat:" + lat + "\nLong: " + lng;
/** Getting Address */
} else {
latLongString = "No location found";
addressString = "No location found";
}
//System.out.println("###########" + addressString + lat + lng);
SearchDeals.latPoint=location.getLatitude();
SearchDeals.lngPoint=location.getLongitude();
Deals_route.sourcelati=location.getLatitude();
Deals_route.sourcelong=location.getLongitude();
}
#Override
public void onDestroy() {
super.onDestroy();
//
//Toast.makeText(this, "GPS Service Destroyed", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(locationListener);
System.out.println("########### inside ONDESTROY GPS listener removed");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
//Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I've just tested the above code on my device and everything is working smoothly, not sure what is the problem at your end.
Important notes:
Please make sure you have the permission to access GPS location in your manifest file
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
The code may not work properly on the emulator , better test on actual device. if you don't have access to one , please checkout the DMMS Emulator Control to generate location data
Edit:
you need to commit out the Location data related to Network Provider.
and Also remove the textView.setText from your LocationResult object because textView is null. so the fixes:
getLocation(Location location) {
.........
String loc = "Lattitude: "+location.getLatitude()+" longi "+location.getLongitude()+" Accur "+location.getAccuracy()+" Time "+location.getTime() +" "+location.getProvider();
Log.i("Log",loc);
Toast.makeText(MainActivity.this, loc, Toast.LENGTH_LONG).show();
}
and comment out the network code from your MyLocation class
// if(network_enabled)
// lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);

GPS doesn't search on my Android

I'm new on android programation and I have a problem with my aplication.
My Gps just doesn't search for location, or anything else.
And yes, my GPS is tunned on.
The manifest cointains the permitions:
ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.
Could somebody help me?
public class LocationTest extends Activity implements
LocationListener {
private static final String[] A = { "invalid", "n/a", "fine", "coarse" };
private static final String[] P = { "invalid", "n/a", "low", "medium",
"high" };
private static final String[] S = { "out of service",
"temporarily unavailable", "available" };
private LocationManager mgr;
private TextView output;
private String best;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
output = (TextView) findViewById(R.id.output);
log("Location providers:");
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
log("\nBest provider is: " + best);
log("\nLocations (starting with last known):");
if (best != null) {
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
}
}
#Override
protected void onResume() {
super.onResume();
// Start updates (doc recommends delay >= 60000 ms)
if (best != null) {
mgr.requestLocationUpdates(best, 15000, 1, this);
}
}
#Override
protected void onPause() {
super.onPause();
// Stop updates to save power while app paused
mgr.removeUpdates(this);
}
public void onLocationChanged(Location location) {
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
log("\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider) {
log("\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
log("\nProvider status changed: " + provider + ", status="
+ S[status] + ", extras=" + extras);
}
/** Write a string to the output window */
private void log(String string) {
output.append(string + "\n");
}
/** Write information from all location providers */
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String provider : providers) {
dumpProvider(provider);
}
}
/** Write information from a single location provider */
private void dumpProvider(String provider) {
LocationProvider info = mgr.getProvider(provider);
StringBuilder builder = new StringBuilder();
builder.append("LocationProvider[")
.append("name=")
.append(info.getName())
.append(",enabled=")
.append(mgr.isProviderEnabled(provider))
.append(",getAccuracy=")
.append(A[info.getAccuracy() + 1])
.append(",getPowerRequirement=")
.append(P[info.getPowerRequirement() + 1])
.append(",hasMonetaryCost=")
.append(info.hasMonetaryCost())
.append(",requiresCell=")
.append(info.requiresCell())
.append(",requiresNetwork=")
.append(info.requiresNetwork())
.append(",requiresSatellite=")
.append(info.requiresSatellite())
.append(",supportsAltitude=")
.append(info.supportsAltitude())
.append(",supportsBearing=")
.append(info.supportsBearing())
.append(",supportsSpeed=")
.append(info.supportsSpeed())
.append("]");
log(builder.toString());
}
/** Describe the given location, which might be null */
private void dumpLocation(Location location) {
if (location == null)
log("\nLocation[unknown]");
else
log("\n" + location.toString());
}
}
I normally don't do this, but I almost have to go.
This is the code I use, it works. (just put this in a new project).
I didn't clean it, because I ripped it from my other project, but it does work, when you make a new project and just copy/paste this.:
import java.util.Timer;
import java.util.TimerTask;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class MainActivity extends Activity {
Timer timer1;
LocationManager lm;
boolean gps_loc = false;
boolean gps_enabled=false;
boolean network_enabled=false;
double lat;
double lng;
String gps_location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
public void gotLocation(final Location location) {
try {
lat = location.getLatitude();
lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
String sLat;
String sLng;
sLat = Double.toString(lat);
sLng = Double.toString(lng);
gps_location = sLat + " " + sLng;
Toast.makeText(getBaseContext(), "We got gps location!",
Toast.LENGTH_LONG).show();
System.out.println("We got gps");
System.out.println("lat = "+lat);
System.out.println("lng = "+lng);
}
} catch (Exception e) {
}
}
};
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(), 35000);
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);
}
}
Also add this in manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
No time to explain now, maybe tomorrow if you still need it.
It prints the latitude and longitude in your logcat.

How to get longitude and latitude of mobile device?

I'm working on a project in which I need to find nearest places to the mobile device (Example: display a list of hotels ordered by the nearest first.) I want to get the longitude and latitude of the mobile phone. The problem is that I want to get them in a class that is NOT an activity and it doesn't have a OnCreate method (The datasource class which contains all the methods dealing with the database). What should I write? and where exactly should I write it?
Please keep it simple! Thank you :)
The activity would need to pass the context (may require passing the actual activity) to the class. After that you should follow this question as it is essentially a duplicate.
How do I get the current GPS location programmatically in Android?
I use this class to grab location:
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);
}
}
And to use this class, you can do something like
locationResult = new LocationResult() {
public void gotLocation(final Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
};
myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);

Not able to get Longitude and Latitude in android

Even though the GPS is on and network is full sometime i am not able to get the lagitude and latitude values of current location but sometimes i am able to get the values sometimes its showing latitude and longitude as 0....can someone help me.
Here is the code which i am using:
package com.fitness24.my24;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
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.scheduleAtFixedRate(new GetLastLocation(), 0, 5000);
return true;
}
public void removeGPS()
{
try {
if(lm != null )
{
timer1.cancel();
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
lm.removeUpdates(locationListenerGps);
locationListenerGps = null;
}
if(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
lm.removeUpdates(locationListenerNetwork);
locationListenerNetwork = null;
}
lm = null;
}
} catch (Exception e) {
}
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
locationResult.gotLocation(location);
}
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) {
locationResult.gotLocation(location);
}
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() {
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);
}
}
/////////////////getting current location///////////////////////////
private void getCurrentLocation(){
try {
Log.e("", "showmap location triggered" + Singleton.getSingletonForXml().sLat + ""
+ Singleton.getSingletonForXml().sLng);
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
if (location != null) {
Singleton.sLat = location.getLatitude();
Singleton.sLng= location.getLongitude();
Log.e("", "showmap location triggered" + Singleton.getSingletonForXml().sLat + ""
+ Singleton.getSingletonForXml().sLng);
if(myLocation != null)
{
myLocation.removeGPS();
Log.i("location", "location acheived and remove gps - inside");
}
}
}
};
myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
}
I would suggest to try this code, I use this code too, and works like a charm:
package com.fitness24.my24;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
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){
System.out.println("gps and/or network disabled");
return false;
}
if(gps_enabled){
System.out.println("gps enabled");
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(network_enabled)
System.out.println("network enabled");
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 25000);
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);
}
}
Then in your main class:
import com.fitness24.my24.MyLocation.LocationResult;
import android.location.Location;
Then also add this in your main, to call/recieve the gps:
private void locationClick() {
myLocation.getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
public void gotLocation(final Location location) {
try {
double lat = location.getLatitude();
double lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
String sLat;
String sLng;
sLat = Double.toString(lat);
sLng = Double.toString(lng);
gps_location = sLat+" "+sLng;
Toast.makeText(getBaseContext(), "We got gps location!", Toast.LENGTH_LONG)
.show();
}
}catch (Exception e) {
}
}
};
this locationClick() is on onClick event of my button (the button to call/recieve gps info)
Also, don't forget to add this in your manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
It is Simple,
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
And dont forget to use this Permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Add the following permissions in your manifest:
<uses-permission android:name="android.permission.ACCESS_GPS"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Categories

Resources