mapbox location GPS not work - android

helo,
i have a strange problem with app - when i use google's api for user location, the gps starts in second and goes to locate. but if i use mapbox, it takes up to 15 minutes to do what it does, then i have to turn off the screen and on again to show the gps logo at the bottom of the screen, then to turn off and on again to begin location. what could makes that. I have searched everywhere on the web for similar problems, but I found nothing. I used everything as it is described in http://www.mapbox.com for making it, and the problem still exists.
Here is the code of Main activity:
import android.arch.lifecycle.Lifecycle;
import android.location.Location;
import android.location.LocationManager;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.CameraMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;
import java.util.List;
public class MbooooActivity extends AppCompatActivity implements OnMapReadyCallback,
LocationEngineListener, PermissionsListener{
private MapView mapView;
private MapboxMap mbm;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private LocationLayerPlugin locationLayerPlugin;
private Location lokation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,getString(R.string.toke));
setContentView(R.layout.activity_mboooo);
mapView=(MapView)findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
#Override
public void onMapReady(MapboxMap mapboxMap) {
mbm=mapboxMap;
enableLocation();
}
private void enableLocation(){
if(PermissionsManager.areLocationPermissionsGranted(this)){
initialiseLocationEngine();
initialiseLocationLayer();
}else{
permissionsManager=new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings("MissingPermission")
private void initialiseLocationEngine(){
locationEngine=new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location prevlok=locationEngine.getLastLocation();
if(prevlok!=null){
lokation=prevlok;
setCamera(prevlok);
}else{
locationEngine.addLocationEngineListener(this);
}
}
#SuppressWarnings("MissingPermission")
private void initialiseLocationLayer(){
locationLayerPlugin=new LocationLayerPlugin(mapView,mbm,locationEngine);
locationLayerPlugin.setLocationLayerEnabled(true);
locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
Lifecycle lifecycle=getLifecycle();
lifecycle.addObserver(locationLayerPlugin);
}
private void setCamera(Location location){
mbm.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),
location.getLongitude()),16.0));
}
#SuppressWarnings("MissingPermission")
#Override
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if(location!=null){
lokation=location;
setCamera(lokation);}
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if(granted){
enableLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
permissionsManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
#SuppressWarnings("MissingPermission")
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
if(locationEngine!=null){
locationEngine.requestLocationUpdates();
locationEngine.addLocationEngineListener(this);}
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
if(locationEngine!=null){
locationEngine.removeLocationEngineListener(this);
locationEngine.removeLocationUpdates();}
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
locationEngine.removeLocationEngineListener(this);
locationEngine.removeLocationUpdates();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
locationEngine.removeLocationUpdates();
locationEngine.removeLocationEngineListener(this);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}

You should listen to location updates independently from last location:
private void initialiseLocationEngine(){
locationEngine=new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
locationEngine.addLocationEngineListener(this);
Location prevlok=locationEngine.getLastLocation();
if(prevlok!=null){
lokation=prevlok;
setCamera(prevlok);
}
}
Additionally you can set:
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.setInterval(0);
locationEngine.setFastestInterval(1000);

Related

Unable to display current location in Logs using LocationListener android studio 2.3

I am trying To get the current location of the user and display it in Logs
Here is my Main Activity Java Code
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
LocationManager locationManager;
LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("Location",location.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//If the device is running version older than Marshmallow
if(Build.VERSION.SDK_INT<23)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
else
{
//Checking if it has permission access
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
//ask for permission
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
else
{
//we have permission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
}
}
But I don't see The sales tag in my Logs, Here are the corresponding Logs:
Here are My Logs
I am new to Maps in Android , so I am not particularly sure where my code goes awry.
At first you need to Move LocationListener outside of onCreate():
public class MainActivity extends AppCompatActivity {
LocationManager locationManager;
LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT<23)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
else
{
//Checking if it has permission access
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
//ask for permission
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
else
{
//we have permission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
}
}
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("Location",location.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
.....
}
Then, Modify onRequestPermissionResult() as below:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
} else {
Toast.makeText(getApplicationContext(), "Please provide permission.", Toast.LENGTH_LONG).show();
}
break;
}
}
}

Mapbox tracking mode SDK 4.0.0

I'm using android Mapbox SDK 4.0.0 and I cann't set center of map when location changed. I don't understand how to use MyLocationTrackingMode. Or how to recive current latitude and longitude and past them to CameraPosition. Can somebody help me, please? Thanks in advance!
package com.detores.wristmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.constants.Style;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
public class MainActivity extends AppCompatActivity {
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a mapView
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
// Set map style
mapboxMap.setStyleUrl(Style.MAPBOX_STREETS);
// Set the camera's starting position
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(50.0051, 36.3562)) // set the camera's center position
.zoom(12) // set the camera's zoom level
.build();
// Move the camera to that position
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mapboxMap.setMyLocationEnabled(true);
}
});
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}
if I understand what you are trying to accomplish then this code snippet might help you get started:
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
public class MainActivity extends AppCompatActivity implements MapboxMap.OnMyLocationChangeListener {
private MapboxMap map;
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
mapboxMap.setOnMyLocationChangeListener(MainActivity.this);
mapboxMap.setMyLocationEnabled(true);
}
});
}
#Override
public void onMyLocationChange(#Nullable Location location) {
if (location != null) {
map.easeCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
Hope this helps you out!

Geo Location Co-ordinates using GooglePlayService

I have copied the below code from google (don't remember the URL) which runs fine on command click listner event , i want to know how can i use/call the same java class (GoogleplayServiceLocation) from my MainActivity class
package com.dbprox.tagpic;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
/**
* Created by user on 24/1/2016.
*/
public class GoogleplayServiceLocation extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener{
TextView TxtViewlat;
TextView TxtViewlon;
// private final Context context;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST=1000;
private Location mLastLocation;
private GoogleApiClient mGoogleApliClient;
private boolean mRequestLocationUpdates=false;
private LocationRequest mLocationRequest;
private static int UPDATE_INTERVAL=10000;
private static int FASTEST_INTTERVAL=5000;
private static int DISPLACEMENT =10;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(checkPlayServices()){
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
public void GoogleplayServiceLocations (Context context)
{
// this.context=context;
if(checkPlayServices()){
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
#Override
protected void onStart()
{
super.onStart();
if(mGoogleApliClient!=null)
{mGoogleApliClient.connect();}
}
#Override
protected void onResume()
{
super.onResume();
checkPlayServices();
if(mGoogleApliClient.isConnected() && mRequestLocationUpdates ){
startLocationUpdates();
}
}
#Override
protected void onStop()
{
super.onStop();
if(mGoogleApliClient.isConnected())
{
mGoogleApliClient.disconnect();
}
}
#Override
protected void onPause(){
super.onPause();
stopLocationUpdates();
}
private void displayLocation(){
mLastLocation= LocationServices.FusedLocationApi.getLastLocation(mGoogleApliClient);
if(mLastLocation!=null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Toast.makeText(getApplicationContext(),
latitude + " - " + longitude , Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(),"Can'rt connect to location", Toast.LENGTH_LONG).show();
}
}
private void togglePeriodLocationUpdates(){
if(!mRequestLocationUpdates) {
mRequestLocationUpdates=true;
startLocationUpdates();
}
else {
mRequestLocationUpdates=false;
stopLocationUpdates();
}
}
protected synchronized void buildGoogleApiClient(){
mGoogleApliClient=new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
protected void createLocationRequest(){
mLocationRequest=new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
displayLocation();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(), "This device is not supported", Toast.LENGTH_LONG).show();
finish();
}
return true;
}
return false;
}
protected void startLocationUpdates(){
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApliClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
}
protected void stopLocationUpdates(){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApliClient, (com.google.android.gms.location.LocationListener) this);
}
#Override
public void onLocationChanged(Location location) {
mLastLocation=location;
Toast.makeText(getApplicationContext(),"Location Changed",Toast.LENGTH_LONG).show();
displayLocation();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onConnected(Bundle bundle) {
displayLocation();
if(mRequestLocationUpdates){
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApliClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("TAG", "Connection Failed: " + connectionResult.getErrorCode());
}
}

How to update a fragment from another class that isn't an fragment

I'm a beginner of android programming then sorry if this question could seem silly but I need to understand how to update the view from a class that it is not an activity or a fragment. I have created a class that fetch data from the Google Play services API. I need to redirect this data to the fragment. which are the common software design patterns to achieve it?
This is the code but unfortunately it doesn't work
TodayFragment
package com.salvo.weather.android.fragment;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.salvo.weather.android.R;
import com.salvo.weather.android.app.VolleyCallback;
import com.salvo.weather.android.entity.CurrentWeatherEntity;
import com.salvo.weather.android.geolocation.CurrentGeolocation;
/**
* A simple {#link Fragment} subclass.
*/
public class TodayFragment extends Fragment {
private static final String TAG = TodayFragment.class.getSimpleName();
private CurrentGeolocation mCurrentGeolocation;
public TodayFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_today, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCurrentGeolocation = CurrentGeolocation.get(getActivity());
}
#Override
public void onStart() {
super.onStart();
mCurrentGeolocation.getmGoogleApiClient().connect();
renderView();
}
#Override
public void onPause() {
super.onPause();
if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
mCurrentGeolocation.stopLocationUpdates();
}
}
#Override
public void onResume() {
super.onResume();
if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
mCurrentGeolocation.startLocationUpdates();
}
}
#Override
public void onStop() {
super.onStop();
if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
mCurrentGeolocation.stopLocationUpdates();
}
}
public void renderView() {
// check if googleApiClient is connected
if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
mCurrentGeolocation.getmCurrentWeatherRequest().loadData(new VolleyCallback() {
#Override
public void onSuccess(CurrentWeatherEntity currentWeatherEntity) {
Log.i(TAG, currentWeatherEntity.getmCity());
}
});
}
}
}
CurrentGeolocation
package com.salvo.weather.android.geolocation;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.salvo.weather.android.app.VolleyCallback;
import com.salvo.weather.android.client.request.CurrentWeatherRequest;
import com.salvo.weather.android.entity.CurrentGeolocationEntity;
import com.salvo.weather.android.entity.CurrentWeatherEntity;
/**
* Created by mazzy on 30/05/15.
*/
public class CurrentGeolocation
implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
private static final String TAG = CurrentGeolocation.class.getSimpleName();
// SETTING CONSTANTS FOR THE LOCATION
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; //ms
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
private static CurrentGeolocation sCurrentGeolocation;
private boolean mRequestingLocationUpdates;
private Context mAppContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private CurrentGeolocationEntity mCurrentGeolocationEntity;
private CurrentWeatherRequest mCurrentWeatherRequest;
public static CurrentGeolocation get(Context appContext) {
if (sCurrentGeolocation == null) {
sCurrentGeolocation = new CurrentGeolocation(appContext.getApplicationContext());
}
return sCurrentGeolocation;
}
private CurrentGeolocation(Context appContext) {
mAppContext = appContext;
mRequestingLocationUpdates = true;
mCurrentGeolocationEntity = new CurrentGeolocationEntity();
mCurrentWeatherRequest = CurrentWeatherRequest.get(appContext);
buildGoogleApiClient();
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected to GoggleApiClient");
if (mCurrentGeolocationEntity.getmLastLocation() == null) {
mCurrentGeolocationEntity.setmLastLocation(LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient));
mCurrentWeatherRequest.setmCurrentGeolocationEntity(mCurrentGeolocationEntity);
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int i) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: error " + connectionResult.getErrorCode());
}
#Override
public void onLocationChanged(Location location) {
// update the location
mCurrentGeolocationEntity.setmLastLocation(location);
}
public GoogleApiClient getmGoogleApiClient() {
return mGoogleApiClient;
}
public void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
public void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
public CurrentWeatherRequest getmCurrentWeatherRequest() {
return mCurrentWeatherRequest;
}
private synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building Google Api Client");
mGoogleApiClient = new GoogleApiClient.Builder(mAppContext)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
You must create a Listener.
TodayFragment
package com.salvo.weather.android.fragment;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.salvo.weather.android.R;
import com.salvo.weather.android.app.VolleyCallback;
import com.salvo.weather.android.entity.CurrentWeatherEntity;
import com.salvo.weather.android.geolocation.CurrentGeolocation;
/**
* A simple {#link Fragment} subclass.
*/
public class TodayFragment extends Fragment implements CurrentGeoloaction.OnUpdateListener {
private static final String TAG = TodayFragment.class.getSimpleName();
private CurrentGeolocation mCurrentGeolocation;
public TodayFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_today, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCurrentGeolocation = CurrentGeolocation.get(getActivity());
mCurrentGeolocation.setOnUpdateListener(this);
}
#Override
public void onStart() {
super.onStart();
mCurrentGeolocation.getmGoogleApiClient().connect();
renderView();
}
#Override
public void onPause() {
super.onPause();
if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
mCurrentGeolocation.stopLocationUpdates();
}
}
#Override
public void onResume() {
super.onResume();
if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
mCurrentGeolocation.startLocationUpdates();
}
}
#Override
public void onStop() {
super.onStop();
if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
mCurrentGeolocation.stopLocationUpdates();
}
}
#Override
public void onUpdate() {
renderView();
}
public void renderView() {
// check if googleApiClient is connected
if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
mCurrentGeolocation.getmCurrentWeatherRequest().loadData(new VolleyCallback() {
#Override
public void onSuccess(CurrentWeatherEntity currentWeatherEntity) {
Log.i(TAG, currentWeatherEntity.getmCity());
}
});
}
}
}
CurrentGeolocation
package com.salvo.weather.android.geolocation;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.salvo.weather.android.app.VolleyCallback;
import com.salvo.weather.android.client.request.CurrentWeatherRequest;
import com.salvo.weather.android.entity.CurrentGeolocationEntity;
import com.salvo.weather.android.entity.CurrentWeatherEntity;
/**
* Created by mazzy on 30/05/15.
*/
public class CurrentGeolocation
implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
private static final String TAG = CurrentGeolocation.class.getSimpleName();
// SETTING CONSTANTS FOR THE LOCATION
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; //ms
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
private static CurrentGeolocation sCurrentGeolocation;
private boolean mRequestingLocationUpdates;
private Context mAppContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private CurrentGeolocationEntity mCurrentGeolocationEntity;
private CurrentWeatherRequest mCurrentWeatherRequest;
private OnUpdateListener mOnUpdateListener;
public interface OnUpdateListener {
public void onUpdate();
}
public void setOnUpdateListener(Fragment todayFragment) {
this.mOnUpdateListener = (OnUpdateListener) todayFragment;
}
public static CurrentGeolocation get(Context appContext) {
if (sCurrentGeolocation == null) {
sCurrentGeolocation = new CurrentGeolocation(appContext.getApplicationContext());
}
return sCurrentGeolocation;
}
private CurrentGeolocation(Context appContext) {
mAppContext = appContext;
mRequestingLocationUpdates = true;
mCurrentGeolocationEntity = new CurrentGeolocationEntity();
mCurrentWeatherRequest = CurrentWeatherRequest.get(appContext);
buildGoogleApiClient();
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected to GoggleApiClient");
if (mCurrentGeolocationEntity.getmLastLocation() == null) {
mCurrentGeolocationEntity.setmLastLocation(LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient));
mCurrentWeatherRequest.setmCurrentGeolocationEntity(mCurrentGeolocationEntity);
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
mOnUpdateListener.onUpdate();
}
}
#Override
public void onConnectionSuspended(int i) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: error " + connectionResult.getErrorCode());
}
#Override
public void onLocationChanged(Location location) {
// update the location
mCurrentGeolocationEntity.setmLastLocation(location);
}
public GoogleApiClient getmGoogleApiClient() {
return mGoogleApiClient;
}
public void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
public void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
public CurrentWeatherRequest getmCurrentWeatherRequest() {
return mCurrentWeatherRequest;
}
private synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building Google Api Client");
mGoogleApiClient = new GoogleApiClient.Builder(mAppContext)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}

getting gps coordinates while indoors

Here is my code, i cant seem to get the coordinates while using NETWORK_PROVIDER. onLocationChange() does not seem to fire. I will appreciate the help.
package com.networkprovider;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
public class networkProvider extends Activity {
EditText editText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText1=(EditText)findViewById(R.id.editText1);
}
#Override
protected void onStart() {
LocationManager locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener=new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onLocationChanged(Location location) {
String loc=String.valueOf(location.getLatitude())+","+String.valueOf(location.getLongitude());
Toast.makeText(getApplicationContext(),loc, Toast.LENGTH_LONG).show();
//editText1.setText(loc);
}
};
boolean isEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isEnabled)
{
Toast.makeText(getApplicationContext(),"Enabled", Toast.LENGTH_LONG).show();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
}
else
{
Toast.makeText(getApplicationContext(),"Not Enabled!", Toast.LENGTH_LONG).show();
}
super.onStart();
}
}
I ran this code and it returned me my location in a toast
check that you have
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
in your manifest or that the device has network locations turned on :)
It may be a silly answer, but are you sure it Should be triggered?
As long as you stay indoors, as the precision of the network is really low, maybe you can't move enough to trigger onLocationChange(). At my home, network precision is about 1km, so you have to get a really big building to use this kind of data to do localisation...
Antoine

Categories

Resources