Android - get country via GPS errors - android

Hello StackOverflow :)
I have created some code inside my onStart(); method to ensure that the user has GPS enabled so i can figure out in which country is he right now. If GPS is disabled, it should show an alert dialog prompting the user to enable GPS before using the app.
For some reason, it seems like that whole chunk of code isn't working. I have disabled GPS and nothing is happening, no dialog and nothing like that. Why is this happening?
Here is my code:
#Override
protected void onStart() {
super.onStart();
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Geocoder code = new Geocoder(TipCalculatorActivity.this);
try {
Address adr = (Address) code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
CountryName = adr.getCountryCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!gpsEnabled) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("This application requires GPS connectivity to determine your current country, and deliver you accurate tip ratings. Do you wish to turn GPS on?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
TipCalculatorActivity.this.enableLocationSettings();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
TipCalculatorActivity.this.finish();
System.exit(1);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
private void enableLocationSettings() {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
Thanks a lot for any help :)

Location loc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Is may be returning null in your case since your mobile has no cached locations.
So change your code to
if (loc != null) {
Geocoder code = new Geocoder(AbcActivity.this);
try {
Address adr = (Address) code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
// CountryName = adr.getCountryCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
If you need to query current Location.Then you need to have active Data connection or GPS turned on.
Following Snippet will help you
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class ShowLocationActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Finally make sure you have added following permissions.
< uses - permission android: name = "android.permission.ACCESS_FINE_LOCATION" / >
< uses - permission android: name = "android.permission.ACCESS_COARSE_LOCATION" / >

Related

Android: Get current location in onResume activity

I am trying to get current location using GPS. So First I am checking GPS is enable or not. If GPS is disable at that time am showing alert and redirect user to enable GPS from Settings. When GPS is enable then redirect Settings to my App at that time in onResume activity I am getting 0.00 current location. How can I get instant current location when enable GPS.
Thanks in advance.
#Override
protected void onResume() {
super.onResume();
getCurrenLocation();
}
public void getCurrenLocation() {
gps = new GpsTracker(GetLocation.this);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// boolean gps_enabled = false;
// boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (gps_enabled && network_enabled) {
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
if (latitude != 0.0 && longitude != 0.0) {
txtLocation.setVisibility(View.VISIBLE);
txtLong.setVisibility(View.VISIBLE);
txtLat.setVisibility(View.VISIBLE);
txtLocation.setText("Your Location is - \nLat: " + latitude + "\nLong: " + longitude);
txtLong.setText(Double.toString(longitude));
txtLat.setText(Double.toString(latitude));
}
Log.d("latitude onResume:: :: :: ::", String.valueOf(latitude));
Log.d("longitude onResume:: :: :: ::", String.valueOf(longitude));
}
} else if (!gps_enabled && !network_enabled) {
alertDialog();
}
}
#komal It always take time to get the Location , depending upon the provider and the place . GPS take signal from min 3 satellite and do uses trilateration , so depending upon the signal strength and ur location it could take time . Even Google Map app take upto 10 sec to get Lat/Lng sometime. You should use FusedLocationProvider from Google Play services
Try this demo https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates
Have you added the permission to your manifest?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I think it is not possible to get the location immediately after enabling GPS. GPS needs to fix the ambiguities and estimate your location.
If you need a location immediately you can you the coarse location. However, this location is much inaccurate than GPS.
Try this class to get the latitude and longitude
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPSTracker extends Service implements LocationListener {
private Context context;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10;
private static final long MIN_TIME_BW_UPDATES=1000*60*1;
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.context=context;
getLocation();
}
public Location getLocation()
{
try{
locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
showSettingsAlert();
}
else{
this.canGetLocation=true;
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location==null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return location;
}
public void stopUsingGPS()
{
if(locationManager !=null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location!=null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location!=null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert(){
Builder alertDialog=new Builder(context);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled.Do you want to go to the settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And then
GPSTracker gps;
public void getCurrenLocation() {
gps = new GPSTracker(classname.this);
if (gps.canGetLocation) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
}
}
Hope this helps

finding user location in android

I am trying to implement the users location in my android project. I have tried alot on many of the codes found in the internet but nothing worked. Neither the Location Manager nor the Location client also tried the new one GoogleApiClient too. But i don't know where is my mistake. Do we require any of the Api's key to get users location? I have kept my codes below:
Location_Finder2.java
package com.notification.messaging;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
public class Location_Finder2 extends Activity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener{
LocationRequest locationRequest;
LocationClient locationClient;
Location location;
Double longitude = 0.0d;
Double latitude = 0.0d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationClient = new LocationClient(this, this, this);
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
}
#Override
public void onLocationChanged(Location arg0) {
locationClient.removeLocationUpdates(this);
longitude = location.getLongitude();
latitude = location.getLatitude();
Log.i("New Latitude && Longitude:", "Longitude:" + longitude + ", Latitude:" + latitude);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
Log.i("Location_2","dhsjchdjcjdjcjkdjcjdn");
location = locationClient.getLastLocation();
if (location == null){
locationClient.requestLocationUpdates(locationRequest, this);
}
else {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("Latitude && Longitude:", "Longitude:" + longitude + ", Latitude:" + latitude);
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
}
I am not getting any location update waiting for a long time but i don't find what my mistake is.
On the first look it seems that you never connect the LocationClient. If you don't get the Logcat message Log.i("Location_2","dhsjchdjcjdjcjkdjcjdn"); it's a good indicator that you have to call locationClient.connect(); in your onCreate().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationClient = new LocationClient(this, this, this);
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
locationClient.connect();
}
The rest of the code looks ok to get location updates.
First add this permission in Manifest -
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Then add this code in New class
private class MyLocationListener implements LocationListener {
//Implement Location Listener
double latitude, longitude;
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Create instance
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
longitude = location.getLongitude();
latitude = location.getLatitude();
//Implement LocationListener and get coordinates
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
}
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method .
You may also like to check whether GPS is enabled or not -
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}

Not getting Latitude and longitude after every 1 minute in android

I want to make an android program in that I get latitude and longitude in Toast after each 1 minute interval and populated on toast even after my application closed.
I have tried as below,But I only getting on time latitude and longitude,Please tell me what should i do for it to get continuously lat long in toast.My code is as below:
GPStracker.java
package com.epe.trucktrackers;
import java.util.Timer;
import java.util.TimerTask;
import utils.Const;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
private Timer timer;
private long UPDATE_INTERVAL;
public static final String Stub = null;
LocationManager mlocmag;
LocationListener mlocList;
private double lat, longn;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to 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();
}
#Override
public void onLocationChanged(Location location) {
String message = String.format(
"Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
System.out.println(":::::::::::Ne lat longs............!!!" + message);
longitude = location.getLongitude();
latitude = location.getLatitude();
Toast.makeText(mContext, latitude + " " + longitude, Toast.LENGTH_LONG)
.show();
/* UpdateWithNewLocation(location); */
System.out.println(":Location chane");
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Activity.java
package com.epe.trucktrackers;
import org.json.JSONException;
import org.json.JSONObject;
import utils.Const;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import backend.BackendAPIService;
public class MainActivity extends Activity {
EditText et_registration_no;
Button btn_register;
static GPSTracker gps;;
String lat, lng;
private ProgressDialog pDialog;
String udid;
String status;
String tracking_id;
String UDID;
String lati;
String longi;
String registration_no;
int flag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_registration_no = (EditText) findViewById(R.id.et_truck_no);
btn_register = (Button) findViewById(R.id.btn_reg);
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
udid = TelephonyMgr.getDeviceId();
gps = new GPSTracker(MainActivity.this);
btn_register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
gps = new GPSTracker(MainActivity.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(
getApplicationContext(),
"Your Location is - \nLat: " + latitude
+ "\nLong: " + longitude, Toast.LENGTH_LONG)
.show();
lat = latitude + "";
lng = longitude + "";
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
new RegistartionApi().execute();
System.out
.println("::::::::::::::service started:::::::::::::");
}
});
// api call for the REGISTARTION ..!!
}
class RegistartionApi extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
System.out
.println("==========inside preexecute===================");
}
#Override
protected Void doInBackground(Void... arg0) {
String registrationURL = Const.API_REGISTRATION + "?UDID=" + udid
+ "&latitude=" + lat + "&longitude=" + lng
+ "&registration_no="
+ et_registration_no.getText().toString().trim();
registrationURL = registrationURL.replace(" ", "%");
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::Registration url:::::::::::;"
+ registrationURL);
String jsonStr = sh.makeServiceCall(registrationURL,
BackendAPIService.POST);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject c = new JSONObject(jsonStr);
if (jsonObj.has("status")) {
status = jsonObj.getString("status");
{
if (status.equalsIgnoreCase("success")) {
flag = 1;
c = jsonObj.getJSONObject("truck_tracking");
tracking_id = c.getString("tracking_id");
UDID = c.getString("UDID");
lati = c.getString("latitude");
longi = c.getString("longitude");
registration_no = c
.getString("registration_no");
} else {
flag = 2;
Toast.makeText(MainActivity.this, "Failed",
Toast.LENGTH_SHORT).show();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if (flag == 1) {
Toast.makeText(MainActivity.this, "Registration Done",
Toast.LENGTH_SHORT).show();
/*Intent i = new Intent(getApplicationContext(), GPSTracker.class);
startService(i);*/
}
}
}
}
Try this one.
package com.sample.location;
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(), 60*1000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
/**
* Called when the provider is disabled by the user. If requestLocationUpdates is called on an already disabled provider, this method is called immediately.
* #param provider
* the name of the location provider associated with this update.
*/
#Override
public void onProviderDisabled(String provider) {
}
/**
* Called when the provider is enabled by the user.
* #param provider
* the name of the location provider associated with this update.
*/
#Override
public void onProviderEnabled(String provider) {
}
/**
* Called when the provider status changes. This method is called when a provider is unable to fetch a location or if the provider has recently become available after a period of unavailability.
* #param provider
* the name of the location provider associated with this update.
* #param status
* OUT_OF_SERVICE if the provider is out of service, and this is not expected to change in the near future; TEMPORARILY_UNAVAILABLE if the provider is temporarily unavailable but is expected to be available shortly; and AVAILABLE if the provider is currently available.
* #param extras
* an optional Bundle which will contain provider specific status variables.
A number of common key/value pairs for the extras Bundle are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below.
satellites - the number of satellites used to derive the fix
*/
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
/**
* Called when the location has changed.
* There are no restrictions on the use of the supplied Location object.
* #param location
* The new location, as a Location object.
*/
#Override
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
/**
* Called when the provider is disabled by the user. If requestLocationUpdates is called on an already disabled provider, this method is called immediately.
* #param provider
* the name of the location provider associated with this update.
*/
#Override
public void onProviderDisabled(String provider) {
}
/**
* Called when the provider is enabled by the user.
* #param provider
* the name of the location provider associated with this update.
*/
#Override
public void onProviderEnabled(String provider) {
}
/**
* Called when the provider status changes. This method is called when a provider is unable to fetch a location or if the provider has recently become available after a period of unavailability.
* #param provider
* the name of the location provider associated with this update.
* #param status
* OUT_OF_SERVICE if the provider is out of service, and this is not expected to change in the near future; TEMPORARILY_UNAVAILABLE if the provider is temporarily unavailable but is expected to be available shortly; and AVAILABLE if the provider is currently available.
* #param extras
* an optional Bundle which will contain provider specific status variables.
A number of common key/value pairs for the extras Bundle are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below.
satellites - the number of satellites used to derive the fix
*/
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
/**
* The GPS location and Network location to be calculated
* in every 5 seconds with the help of this class
*
*/
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);
}
}
/**
* This abstract class is used to get the location from other class.
*
*/
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
In your Activity.java
LocationManager myLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
MyLocation myLocation = new MyLocation();
myLocation.getLocation(getApplicationContext(), locationResult);
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
};

show complete address instead of longitude and latitude

I am working on GPS location whereby i get the longitude and latitude but i dont know how to get the complete address instead of this. i have followed a tutorial for my code and saw many posts to find out how can i get the address based on this but coudnt find any probable solution
Following is my code:
GpsTracker.java
package com.example.gpslocator;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GpsTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GpsTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GpsTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to 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();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
MainActivity.java
package com.example.gpslocator;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnShowLocation;
TextView textview;
// GPSTracker class
GpsTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GpsTracker gpsTracker = new GpsTracker(this);
btnShowLocation = (Button) findViewById(R.id.button1);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GpsTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Use the received location and feed it to the GeoCoder or the Geocoding API.
The GeoCoder is part of the SDK since API Level 1 and results in an ArrayList of Address Objects.
Geocoding is a web-service, which responses a JSON.
Both solutions are delivering detailed information and can be used for geocoding (location to address) or reverse geocoding (address to location).
Edit:
Use the GeoCoder like this:
if(GeoCoder.isPresent()) {
Geocoder geocoder = new Geocoder(this);
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(latitude, longitude, 1);
if (!addresses.isEmpty()) {
Address address = list.get(0);
// do something with your address
} else {
// No results for your location
}
} catch (IOException e) {
e.printStackTrace();
}
}

how to make my activity not stop working

import android.app.Activity;
public class LocationTracking extends Activity {
Button btnShowLocation;
Button refresh;
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_tracking);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
refresh = (Button) findViewById(R.id.refresh);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(LocationTracking.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
((TextView)findViewById(R.id.latitude)).setText(Double.toString(latitude));
((TextView)findViewById(R.id.longitude)).setText(Double.toString(longitude));
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((TextView)findViewById(R.id.latitude)).setText("");
((TextView)findViewById(R.id.longitude)).setText("");
}
});
}
}
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to 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();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
i found this gps tracking activity on the net i tried it already and it works perfectly but i encountered a problem later on.when i start a new activity it stop on running what i want to do is for it not to stop even if i start i new activity example if someone is calling or im texting the gps tracking will still track my location where did i make my mistake?
use this code, registered the LocationManager in onchangeLocation() method.
public class NewLocationListener implements android.location.LocationListener {
private final static String TAG = "LocationListener";
private Context context = null;
private LocationManager locationManager = null;
private double latitude = 0.0;
private double longitude = 0.0;
/*public String newlatitude=null;
public String newlongitude=null;*/
private Location gpslocation=null;
public void setDefault() {
Log.v(TAG + ".setDefault", "GPS Co-ordinates initialised");
latitude = 0.0;
longitude = 0.0;
}
public NewLocationListener(Context ctx) {
Log.v(TAG + ".LocationListener", "LocationListener constructor called");
context = ctx;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
public void onProviderDisabled(String provider) {
Log.v(TAG + ".onProviderDisabled", "onProviderDisabled method called");
}
public void onProviderEnabled(String provider) {
Log.v(TAG + ".onProviderEnabled", "onProviderEnabled method called");
}
public void onLocationChanged(Location location) {
gpslocation=location;
Log.v(TAG + ".onLocationChanged", "onLocationChanged method called");
//Toast.makeText(context, "onLocationChanged called", Toast.LENGTH_SHORT).show();
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (gpslocation != null) {
setLocationCoordinates(gpslocation);
} else {
Log.v(TAG + ".onLocationChanged", "couldn't get gps using onLocationChange");
getLastKnownLocation();
}
}
public void setLocationCoordinates(Location location) {
try {
double latNew = (location.getLatitude());
double lonNew = (location.getLongitude());
if (latNew != 0.0 && lonNew != 0.0) {
Log.v(TAG + ".onLocationChanged", "New location co-ordinates are not 0");
/* setLatitude(latNew);
setLongitude(lonNew);*/
/*
* latitude = latNew; longitude = lonNew;
*/
String newlatitude=Double.toString(latNew);
String newlongitude=Double.toString(lonNew);
Log.v(TAG, "new latitude is" + newlatitude+" new longitude is" + newlongitude);
//Toast.makeText(context, "lat: " + newlatitude+" lon: " + newlongitude, Toast.LENGTH_SHORT).show();
} else {
//Toast.makeText(context, "we got 0.0 value ", Toast.LENGTH_SHORT).show();
Log.v(TAG + ".onLocationChanged", "we got 0.0 value ");
}
} catch (Exception e) {
Log.v(TAG + ".onLocationChanged.Exception", "Exception is " + e);
}
}
public void getLastKnownLocation() {
Location location = locationManager.getLastKnownLocation(getBestProvider());
gpslocation=location;
if (gpslocation != null) {
//Toast.makeText(context, "LastKnownLocation called", Toast.LENGTH_SHORT).show();
setLocationCoordinates(gpslocation);
} else {
//Toast.makeText(context, "couldn't get LastKnownLocation", Toast.LENGTH_SHORT).show();
Log.v(TAG + ".onLocationChanged","couldn't get gps using lastKnownLocation");
}
}
public String getBestProvider() {
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
String bestProvider = locationManager.getBestProvider(criteria, true);
return bestProvider;
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v(TAG + ".onStatusChanged", "onStatusChanged method called");
}
public double getLatitude() {
if (gpslocation != null) {
latitude = gpslocation.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (gpslocation != null) {
longitude = gpslocation.getLongitude();
}
return longitude;
}

Categories

Resources