I am trying to send coordinates of my position to the web service, I have a class called "LocationService" that should do this, but at the moment of executing the application nothing happens ...
LocationService
public class LocationService extends Service implements LocationListener{
public String LOG = "Log";
UserSessionManager session;
private Context mContext = null;
boolean isGPSEnabled = false;
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 = 0; // 0 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000; // 1 second
// Declaring a Location Manager
protected LocationManager locationManager;
public LocationService(Context context) {
this.mContext = context;
}
public LocationService() {
super();
mContext = LocationService.this;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.i(LOG, "Service started");
Log.i("asd", "This is sparta");
HashMap<String, String> user = session.obtenerRolyId();
String usuarioId = user.get(UserSessionManager.KEY_ID);
new SendToServer().execute(Double.toString(getLocation().getLongitude()), Double.toString(getLocation().getLatitude()),usuarioId);
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(LOG, "Service created");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG, "Service destroyed");
}
class SendToServer extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... la) {
try {
HttpURLConnection urlConnection = null;
String posicionActual = "";
BufferedReader reader = null;
OutputStream os = null;
InputStream inputStream = null;
Log.i("string", la[0]);
String longi = la[0]; // Recibo la longitud.
String lati = la[1]; // Recibo la latitud.
String idUsuario = la[2]; // Recibo Id del usuario.
JSONObject coordenadas = new JSONObject();
coordenadas.put("Latitud",lati);
coordenadas.put("Longitud",longi);
posicionActual = coordenadas.toString();
URL url = new URL("http://localhost:8081/odata/Usuarios("+idUsuario+")/ActualizarPosicion");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.connect();
os = new BufferedOutputStream(urlConnection.getOutputStream());
os.write(posicionActual.getBytes());
} catch (Exception e) {
Log.i("error", e.toString());
}
return "call";
}
}
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) {
//updates will be send according to these arguments
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
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;
}
#Override
public void onLocationChanged(Location location) {
//Llamo al servidor cada segundo y le envío mi posición
HashMap<String, String> user = session.obtenerRolyId();
String usuarioId = user.get(UserSessionManager.KEY_ID);
new SendToServer().execute(Double.toString(getLocation().getLongitude()),Double.toString(getLocation().getLatitude()), usuarioId);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}}
I call my service from the activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_map);
startService(new Intent(UserMapActivity.this, LocationService.class));}
To start, move the permission check to the onStartCommand, you only have to check it once. And please, ask the user to grant you the permission, it is this simple:
ActivityCompat.requestPermissions(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION, SINGLE_PERMISSION_REQUEST_CODE);
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
d(TAG,"Permission " + permissions[0] +" granted");
}
}
Then, in the onLocationChange replace this:
new SendToServer().execute(Double.toString(getLocation().getLongitude()), Double.toString(getLocation().getLatitude()),usuarioId);
with this
new SendToServer().execute(Double.toString(location.getLongitude()), Double.toString(location.getLatitude()),usuarioId);
You already have the last location from the provider, you don't have to get it again from the getLastKnownLocation
In the server connection you should add this to check everything worked out well:
os.flush();
os.close();
int serverResponse = urlConnection.getResponseCode();
String serverMsg = urlConnection.getResponseMessage();
urlConnection.disconnect();
Log.d(TAG, "Code: " + serverResponse + " - Menssage: " + serverMsg);
Related
Here is my code:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
LocationListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
GoogleMap mMap;
SupportMapFragment mapFragment;
LocationRequest mLocationRequest;
GoogleApiClient client;
Location mLastLocation;
Marker mCurrLocationMarker;
LatLng latLongCurrent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getSupportActionBar().setTitle("Map location");
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void findRestaurant(View view) {
StringBuilder stringBuilder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
stringBuilder.append("location=" + latLongCurrent.latitude + "," + latLongCurrent.longitude); //error attempt to read from field 'double...on a null object reference
stringBuilder.append("&radius=" + 1000);
stringBuilder.append("&keyword=" + "restaurant");
stringBuilder.append("&key=" + getResources().getString(R.string.google_places_key));
String url = stringBuilder.toString();
Object dataTransfer[] = new Object[2];
dataTransfer[0] = mMap;
dataTransfer[1] = url;
NearbySearch nearbySearch = new NearbySearch(this);
nearbySearch.execute(dataTransfer);
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (client != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.map_options, menu);
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initializing the Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(client, mLocationRequest, this);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Change the map type based on the user's selection.
switch (item.getItemId()) {
case R.id.normal_map:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
return true;
case R.id.hybrid_map:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
return true;
case R.id.satellite_map:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
return true;
case R.id.terrain_map:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("My current Position");
mCurrLocationMarker = mMap.addMarker(markerOptions);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(MapsActivity.this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept this to use the location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
}).create().show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (client == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Permission is denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
private void moveCamera(LatLng latLang, float zoom, String title) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLang, zoom));
//writing the code to drop the pin or marker
MarkerOptions options = new MarkerOptions().position(latLang).title(title);
mMap.addMarker(options);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
and this is my class NearbySearch.java code below:
public class NearbySearch extends AsyncTask<Object, String, String> {
GoogleMap mMap;
String url;
InputStream is;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String data;
public NearbySearch(MapsActivity mapsActivity) {
}
#Override
protected String doInBackground(Object... objects) {
//requesting for the response from the google places API
mMap = (GoogleMap) objects[0];
try {
URL myUrl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) myUrl.openConnection();
is = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
//Receiving the data from json
data = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject parentObject = new JSONObject(s);
JSONArray resultArray = parentObject.getJSONArray("results");
for (int i = 0; i < resultArray.length(); i++) {
JSONObject jsonObject = resultArray.getJSONObject(i);
JSONObject locationObject = jsonObject.getJSONObject("geometry").getJSONObject("location");
String latitude = jsonObject.getString("lat");
String longitude = jsonObject.getString("lng");
JSONObject nameObject = resultArray.getJSONObject(i);
String nameRestaurant = nameObject.getString("name");
String vicinity = nameObject.getString("vicinity");
LatLng latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.title(vicinity);
markerOptions.position(latLng);
mMap.addMarker(markerOptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
I'm successfully fetching the user's current location but cannot find the solution to find the nearby restaurants from the current location. Please help to get rid of it as I'm stuck for 2 days here. Kindly tell me if any other solution is there too. Thanks!
For my app, I need to get the location of the user, to fetch corresponding data from a server. The problem is that the code I use doesn't properly return the location when it's opened the first time. After restarting the app once it works just fine. I searched the other questions and found out, that if you use getLastKnownLocation and there is no location since the last reboot, it returns null. But why does it work when the app is restarted? Does it fetch it when it's opened the first time, and how can I make it wait until the location is fetched properly at the first opening then?
The code of my MainActivity:
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
} else {
progressBar.setVisibility(View.VISIBLE);
GPSClass gt = new GPSClass(getActivity().getApplicationContext());
Location location = gt.getLocation();
if (location == null) {
//Toast
} else {
lat = location.getLatitude();
lon = location.getLongitude();
}
new GetContacts().execute();
}
And the GPSClass:
public class GPSClass implements LocationListener {
Context context;
public GPSClass(Context context) {
super();
this.context = context;
}
public Location getLocation(){
if (ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
Log.e("fist","error");
return null;
}
try {
LocationManager lm = (LocationManager) context.getSystemService(LOCATION_SERVICE);
boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,10,this);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return loc;
}else{
Log.e("sec","error");
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
Here is the full tutorial
I shared a tutorial link follow that link.
Call this below method. It will return value; when lat and long is found. Until object is null or doesn't return any value your app must be idle or show some progress value or tell the user to wait.
InitGeoLocationUpdate.locationInit(SplashScreen.this,
object -> {
double latitude = object.latitude;
double longitude = object.longitude;
Lg.INSTANCE.d(TAG, "Current Location Latitude: " + latitude + " Longitude: " +
longitude);
});
Try this this will not give you null current location
class GetLastLocation extends TimerTask {
LocationManager mlocManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListenerTmp = new CustomLocationListener();
private final Handler mLocHandler;
public GetLastLocation(Handler mLocHandler) {
this.mLocHandler = mLocHandler;
}
#Override
public void run() {
timer.cancel();
mlocManager.removeUpdates(mlocListenerTmp);
Location location = mlocManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
{
if (mlocListenerTmp != null) {
mlocManager.removeUpdates(mlocListenerTmp);
}
currentLocation = location;
}
if (location != null) {
String message = String.format(
"Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Log.d("loc", " :" + message);
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Log.d(
"loc",
":No GPS or network signal please fill the location manually!");
location = mlocManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
currentLocation = location;
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", false);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
}
}
}
}
call it like this in your MainActivity
timer.schedule(new GetLastLocation(mLocHandler), 3000);
and the customLocationclass is as follows:
public class CustomLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
currentLocation = loc;
String Text = "My current location is: " + "Latitud = "
+ loc.getLatitude() + "Longitud = " + loc.getLongitude();
Log.d("loc", "onLocationChanged" + Text);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
The code works in my phone properly but doesn't works sometime. Also, this code doesn't work in other phone properly. I have tried many times. And while sending this app's apk file through xender the installation fails. Please help to improve my code so that it works properly in all phone when location is turned ON.
Mainactivity.java
public class MainActivity extends AppCompatActivity {
TextView result;
Double latitude, longitude;
Geocoder geocoder;
List<Address> addressList;
Getgps gps;
Context mContext;
protected LocationManager locationManager;
boolean isGPSEnabled = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.abcd);
geocoder = new Geocoder(this, Locale.getDefault());
mContext = this;
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled)
{
getlonglat(); //check location
if(CheckInternetConnection(MainActivity.this)) {
getaddress();
// getlocation
if(result.getText().toString().matches(""))
{
Toast.makeText(mContext, "Poor Internet Connection", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),"No internet Connection",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(),"Turn ON Your Location",Toast.LENGTH_LONG).show();
showgpsSettingsAlert();
startActivity(new Intent(MainActivity.this, Main2Activity.class));
Toast.makeText(mContext, " after delay khatey", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void getlonglat() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else {
Toast.makeText(mContext, "GPS Permission Granted", Toast.LENGTH_SHORT).show();
gps = new Getgps(mContext, MainActivity.this);
// Check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is - \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
}
}
}
public void getaddress() {
try {
addressList = geocoder.getFromLocation(latitude, longitude, 1);
String address = addressList.get(0).getAddressLine(0);
String area = addressList.get(0).getLocality();
String city = addressList.get(0).getAdminArea();
String country = addressList.get(0).getCountryName();
String postalcode = addressList.get(0).getPostalCode();
String fullAddress = address + ", " + area + ", " + city + ", " + country + ", " + postalcode;
Toast.makeText(mContext, "Internet Permission Granted", Toast.LENGTH_SHORT).show();
result.setText(fullAddress);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static boolean CheckInternetConnection(Context context) {
ConnectivityManager connectivity =
(ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
public void showgpsSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setCancelable(false);
this.setFinishOnTouchOutside(false);
alertDialog.setTitle("GPS Setting");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("OK ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(mContext, "Sorry we cannot proceed", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();// Showing Alert Message
}
}
Getgps.java
package com.example.bibash28.locationfinal2;
/**
* Created by Bibash28 on 11/3/2017.
*/
public class Getgps extends Service
{
private Context mContext; // Flag for GPS status
boolean isGPSEnabled = false; // Flag for network status
boolean canGetLocation = false;
Location location; // Location
Double latitude,longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000;// The minimum distance to change Updates in meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;// 10 meters// The minimum time between updates in milliseconds// 1 minute
Activity activity;
protected LocationManager locationManager;
public Getgps(Context context, Activity activity)
{
this.mContext = context;
this.activity = activity;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
this.canGetLocation = true;
if (isGPSEnabled) {
if (location == null) {
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
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;
}
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//Function to get latitude
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
// Function to get longitude
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
//Function to check GPS/Wi-Fi enabled #return boolean
public boolean canGetLocation()
{
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
I'm working with Weather Underground API where I can get weather of a place in 2 ways:
Writing directly the name of the city and nation (example:http://api.wunderground.com/api/*MyKey*/conditions/q/It/Venice.json)
Get the weather of every place have latitude/longitude (example:http://api.wunderground.com/api/*MyKey*/conditions/q/45.43972222,12.33194444.json)
I'm interested in the second way so I'm trying to get my position (that works in an Activity).
FirstActivity.java: (the position is displayed with no problem)
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
TextView textview1 = (TextView)findViewById(R.id.fieldLatitude);
textview1.setText(stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
TextView textview2 = (TextView)findViewById(R.id.fieldLongitude);
textview2.setText(stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
}
AsyncTask:
public class Conditions extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_conditions);
new WeatherConditions(this).execute();
}
private class WeatherConditions extends AsyncTask<String, String, String> {
private Context mContext;
public WeatherConditions (Context context){
mContext = context;
}
#Override
protected String doInBackground(String... uri) {
GPSTracker gpsTracker = new GPSTracker(mContext);
String latitudine = null;
String longitudine = null;
if (gpsTracker.canGetLocation())
{
latitudine = String.valueOf(gpsTracker.latitude);
longitudine = String.valueOf(gpsTracker.longitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
String responseString = null;
try {
HttpClient client = new DefaultHttpClient();
URI apiCall = new URI("api.wunderground.com/api/51cda8abeca78e10/conditions/q/"
+ latitudine
+","
+ longitudine
+".json");
HttpGet request = new HttpGet();
request.setURI(apiCall);
HttpResponse response = client.execute(request);
responseString = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
Log.e("TAG", "some sort of problem encountered", e);
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
...
}
}
}
Where I get this message in the LogCat: Can't create handler inside thread that has not called Looper.prepare()
Here's GPSTracker.java:
public class GPSTracker extends Service implements LocationListener{
private final Context mContext;
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; //10 metters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
}
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);
updateGPSCoordinates();
}
}
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);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
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()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Attenzione!");
alertDialog.setMessage("Abilita il GPS");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("CLOSE", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
public List<Address> getGeocoderAddress(Context context)
{
if (location != null)
{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try
{
return geocoder.getFromLocation(latitude, longitude, 1);
}
catch (IOException e)
{
//e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}
public String getAddressLine(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getAddressLine(0);
}
else
{
return null;
}
}
public String getLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getLocality();
}
else
{
return null;
}
}
public String getSubLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getSubLocality();
}
else
{
return null;
}
}
public String getPostalCode(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getPostalCode();
}
else
{
return null;
}
}
public String getCountryName(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getCountryName();
}
else
{
return null;
}
}
#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 intent)
{
return null;
}
In GPSTracker.java, since getLocation() has context of async task attached to it and looper is not attached to it.
A quick workaround to solve this problem is add Looper.getMainLooper() with requestLocationUpdates, this will attach main looper thread callback with request.
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this, Looper.getMainLooper()
);
Have a good day, for 2 days I can not solve the problem.
took the app is very similar to that
http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
everything works well, I get the GPS coordinates.
process would then obtain the coordinates + sending them to the server to be moved to a background service and that there was a problem, come coordinates 0.0 0.0
MainActivity.java (its all workin)
public class MainActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
final String LOG_TAG = "myLogs";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.button1);
// show location button click event
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();
// #/mygps.php?lat=33.995834&lon=22.93707×tamp=1375235923365&hdop=16.0&altitude=107.65327&speed=0.0
new RequestTask().execute("http://map.domain.ru/mygps.php?lat="+latitude+"&lon="+longitude+"×tamp=1375235923365&hdop=16.0&altitude=107.65327&speed=0.0");
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
public void onClickStart(View v) {
startService(new Intent(this, MyService.class));
}
public void onClickStop(View v) {
stopService(new Intent(this, MyService.class));
}
}
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
GPSTracker.java
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;
// 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;
}
/**
* 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;
}
}
MyService.java
public class MyService extends Service {
final String LOG_TAG = "myLogs";
// GPSTracker class
GPSTracker gps;
MyBinder binder = new MyBinder();
Timer timer;
TimerTask tTask;
long interval = 10000;
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "onCreate");
// timer = new Timer();
// schedule();
}
public void schedule() {
if (tTask != null) tTask.cancel();
if (interval > 0) {
tTask = new TimerTask() {
public void run() {
Log.d(LOG_TAG, "run");
gps = new GPSTracker(getApplicationContext()); // also tried MyService.this
if(gps!=null){
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.d(LOG_TAG, "geo"+latitude+" lon"+longitude);
new RequestTask().execute("http://map.domain.ru/mygps.php?lat="+latitude+"&lon="+longitude+"×tamp=1375235923365&hdop=16.0&altitude=107.65327&speed=0.0");
}
}else{
Log.d(LOG_TAG, "GPS null");
}
}
};
timer.schedule(tTask, 10000, interval);
}
}
long upInterval(long gap) {
interval = interval + gap;
schedule();
return interval;
}
long downInterval(long gap) {
interval = interval - gap;
if (interval < 0) interval = 0;
schedule();
return interval;
}
// public IBinder onBind(Intent arg0) {
// Log.d(LOG_TAG, "MyService onBind");
// return binder;
// }
class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
//}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LOG_TAG, "onStartCommand");
// someTask();
timer = new Timer();
schedule();
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() {
super.onDestroy();
Log.d(LOG_TAG, "onDestroy");
// stopSelf();
timer.cancel();
}
public IBinder onBind(Intent intent) {
Log.d(LOG_TAG, "onBind");
return null;
}
void someTask() {
}
}
Why in the last class instead coordinates come nulls
code
Log.d(LOG_TAG, "geo "+latitude+" lon "+longitude);
write log "geo 0.0 lon 0.0"
this is because on that time gps cannot get location
almost the time when you are in building this happened
and there isnt lastknown location
you just checked that gps enabled
after that you must confident about the location that returned by checking location timestamp by difference between device time and location timestamp