Alex248
Alex248

Reputation: 427

Location updating from network doesn't work after changing location settings

When my location services are disabled and I want to enbale it for using my app, only the GPS provider works, while the network provider doesn't. It wolud work only after restart. I've this problem at nexus4 but on other devices too. I've created a test app with the same issue. I will be grateful if someone would help me to solve this problem.

public class MainActivity extends Activity {

protected static final String TAG = "Gpstest";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    initLocationManager();

}
private void initLocationManager() {

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

}

LocationManager locationManager;

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG,"onLocationChanged "+location.getProvider());

    }
};

@Override
protected void onStop() {
    super.onStop();
    locationManager.removeUpdates(locationListener);
}

}

the manifest

<?xml version="1.0" encoding="utf-8"?>

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />
<!-- Location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.gpstext.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Upvotes: 1

Views: 1016

Answers (2)

Zohra Khan
Zohra Khan

Reputation: 5302

Your code is working fine. Tried in my device With permission

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

And code

public class MainActivity extends Activity {
protected static final String TAG = "Gpstest";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    initLocationManager();

}
private void initLocationManager() {

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}

LocationManager locationManager;

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "onLocationChanged " + location.getProvider());
        Toast.makeText(MainActivity.this, "Lat:" + location.getLatitude()
                +"Long" + location.getLongitude(),Toast.LENGTH_LONG).show();

    }
};

@Override
protected void onStop() {
    super.onStop();
    locationManager.removeUpdates(locationListener);
}
}

Make sure that wi-fi is on.

Upvotes: 0

Atish Agrawal
Atish Agrawal

Reputation: 2877

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

As you can see in the above code, you are assigning two different providers to a single locationManager and the same locationListener.

This implementation results data to be fetched from GPS_Provider and not from Network.

Try using two different locationManagers and different locationListeners to get results from both the providers.

public class MainActivity extends Activity implements
    GooglePlayServicesClient.ConnectionCallbacks,
    GooglePlayServicesClient.OnConnectionFailedListener {

protected static final int START_GPS_SETTINGS = 1;
GoogleMap googleMap;
Dialog alertDialog = null;
LocationManager locationManager = null;
LocationManager GPSlocationManager = null;
LocationManager NetworklocationManager = null;

private LocationClient locationclient;

Location location;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {

        locationclient = new LocationClient(this, this, this);
        locationclient.connect();

    } else {
        Toast.makeText(
                this,
                "Google Play Service Error "
                        + GooglePlayServicesUtil
                                .isGooglePlayServicesAvailable(this),
                Toast.LENGTH_LONG).show();

    }
}

@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;
}

@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();

    googleMap = ((MapFragment) getFragmentManager().findFragmentById(
            R.id.mapFragment)).getMap();

    if (googleMap != null) {

        googleMap.setMyLocationEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
        googleMap.getUiSettings().setAllGesturesEnabled(true);

    }

}

public void locateMe(View view) {

    checkforGPS();

}

private void checkforGPS() {

    // checking whether the gps is enabled on the device or not

    if (!((LocationManager) this.getSystemService(Context.LOCATION_SERVICE))
            .isProviderEnabled(LocationManager.GPS_PROVIDER)) {

        // GPS is not enabled

        // 1. Instantiate an AlertDialog.Builder with its constructor
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        // 2. Chain together various setter methods to set the dialog
        // characteristics
        builder.setMessage(R.string.generic_gps_not_found)
                .setTitle(R.string.generic_gps_not_found_message_title)
                .setPositiveButton(R.string.generic_ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                // User selected yes
                                Intent intent = new Intent(
                                        Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivityForResult(intent,
                                        START_GPS_SETTINGS);
                            }
                        });

        // 3. Get the AlertDialog from create()
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();

    } else {

        // GPS is enabled

        startGettingLocation();
    }

}

public void captureImage(View view) {
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_CANCELED) {

        switch (requestCode) {
        case START_GPS_SETTINGS:

            startGettingLocation();

            break;
        }

    }
}

private void startGettingLocation() {

    getLocationFromLocationClient();

    getLocationFromNetworkPriver();

    getLocationFromGPSPriver();

    final Handler handler1 = new Handler();
    handler1.postDelayed(new Runnable() {
        @Override
        public void run() {
            // Do something after 3000ms
            showDialogBox();

            getLocation();

        }
    }, 20000);

}

public void animateGoogleMap() {

    if (location != null && googleMap != null) {

        LatLng latLng = new LatLng(location.getLatitude(),
                location.getLongitude());

        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
        // googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        googleMap.addMarker(new MarkerOptions().position(latLng).icon(
                BitmapDescriptorFactory
                        .fromResource(R.drawable.trip_start_icon)));

    } else {

        // Something went wrong.
        // Restarting the activity

        reload();
    }

}

/**
 * code for getting the current location
 */

private void showDialogBox() {
    alertDialog = new Dialog(this);

    alertDialog.setCanceledOnTouchOutside(false);
    alertDialog.setCancelable(false);

    alertDialog.setTitle("Location Updates....");

    LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = layoutInflater.inflate(R.layout.dialog_layout, null);

    // Setting Dialog Title
    ((TextView) v.findViewById(R.id.header))
            .setText("Location Updates....");

    // Setting Dialog Message
    ((TextView) v.findViewById(R.id.text_msg))
            .setText("Please wait for updates");

    // Showing Alert Message
    alertDialog.setContentView(v);
    alertDialog.show();

}

private void getLocation() {

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);

    String provider = locationManager.getBestProvider(criteria, false);

    Log.e("provider", provider);

    locationManager.requestLocationUpdates(provider, 1000, 1,
            myLocationListener);

}

private LocationListener myLocationListener = new LocationListener() {

    @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 void onLocationChanged(Location locationBest) {

        if (locationBest == null)
            return;
        Log.e("Best Provider", "Best Provider");
        Log.e("latitude", locationBest.getLatitude() + "");
        Log.e("longitude", locationBest.getLongitude() + "");
        Log.e("accuracy", locationBest.getAccuracy() + "");

        removeLocationUpdatesAndAddMarker(locationBest);

    }
};
private LocationListener myGPSLocationListener = new LocationListener() {

    @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 void onLocationChanged(Location locationGPS) {

        if (locationGPS == null)
            return;

        Log.e("GPS Provider", "GPS Provider");
        Log.e("latitude", locationGPS.getLatitude() + "");
        Log.e("longitude", locationGPS.getLongitude() + "");
        Log.e("accuracy", locationGPS.getAccuracy() + "");

        removeLocationUpdatesAndAddGPSMarker(locationGPS);

    }
};
private LocationListener myNetworkLocationListener = new LocationListener() {

    @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 void onLocationChanged(Location locationNetwork) {

        if (locationNetwork == null)
            return;

        Log.e("Network Provider", "Network Provider");
        Log.e("latitude", locationNetwork.getLatitude() + "");
        Log.e("longitude", locationNetwork.getLongitude() + "");
        Log.e("accuracy", locationNetwork.getAccuracy() + "");

        removeLocationUpdatesAndAddNetworkMarker(locationNetwork);

    }
};

private void removeLocationUpdatesAndAddMarker(
        Location locationFromBestLocationProvider) {

    // Removing the listener from giving the location

    if (locationManager != null) {

        locationManager.removeUpdates(myLocationListener);
        locationManager = null;

    }

    WriteLogToFile.appendLog(
            this.getString(R.string.app_name),
            "BestProvider",
            "BestProvider",
            "Location :\n" + "Latitude:"
                    + locationFromBestLocationProvider.getLatitude()
                    + "\nLongitude:"
                    + locationFromBestLocationProvider.getLongitude()
                    + "\nAccuracy:"
                    + locationFromBestLocationProvider.getAccuracy());

    location = locationFromBestLocationProvider;

    if (alertDialog != null)
        alertDialog.dismiss();

    animateGoogleMap();

}

private void removeLocationUpdatesAndAddGPSMarker(Location locationFromGPS) {

    if (GPSlocationManager != null) {

        GPSlocationManager.removeUpdates(myGPSLocationListener);
        GPSlocationManager = null;

    }

    WriteLogToFile.appendLog(this.getString(R.string.app_name), "GPS",
            "GPS",
            "Location :\n" + "Latitude:" + locationFromGPS.getLatitude()
                    + "\nLongitude:" + locationFromGPS.getLongitude()
                    + "\nAccuracy:" + locationFromGPS.getAccuracy());

    LatLng latLng = new LatLng(locationFromGPS.getLatitude(),
            locationFromGPS.getLongitude());

    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
    // googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    googleMap.addMarker(new MarkerOptions().position(latLng).icon(
            BitmapDescriptorFactory.fromResource(R.drawable.gps_provider)));
}

private void removeLocationUpdatesAndAddNetworkMarker(
        Location locationFromNetwork) {

    if (NetworklocationManager != null) {

        NetworklocationManager.removeUpdates(myNetworkLocationListener);
        NetworklocationManager = null;

    }

    WriteLogToFile.appendLog(
            this.getString(R.string.app_name),
            "Network",
            "Network",
            "Location :\n" + "Latitude:"
                    + locationFromNetwork.getLatitude() + "\nLongitude:"
                    + locationFromNetwork.getLongitude() + "\nAccuracy:"
                    + locationFromNetwork.getAccuracy());

    LatLng latLng = new LatLng(locationFromNetwork.getLatitude(),
            locationFromNetwork.getLongitude());

    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
    // googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    googleMap.addMarker(new MarkerOptions().position(latLng).icon(
            BitmapDescriptorFactory
                    .fromResource(R.drawable.network_provider)));
}

public void reload() {

    Intent intent = getIntent();
    overridePendingTransition(0, 0);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    finish();

    overridePendingTransition(0, 0);
    startActivity(intent);
}

private void getLocationFromLocationClient() {

    if (locationclient != null && locationclient.isConnected()) {
        Location loc = locationclient.getLastLocation();

        WriteLogToFile.appendLog(this.getString(R.string.app_name),
                "LocationClient", "LocationClient",
                "Last Known Location :\n" + "Latitude:" + loc.getLatitude()
                        + "\nLongitude:" + loc.getLongitude()
                        + "\nAccuracy:" + loc.getAccuracy());

        LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());

        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
        // googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        googleMap.addMarker(new MarkerOptions().position(latLng).icon(
                BitmapDescriptorFactory
                        .fromResource(R.drawable.trip_end_icon)));

    }

}

private void getLocationFromGPSPriver() {

    GPSlocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    GPSlocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            1000, 1, myGPSLocationListener);

}

private void getLocationFromNetworkPriver() {

    NetworklocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    NetworklocationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER, 1000, 1,
            myNetworkLocationListener);

}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onDisconnected() {
    // TODO Auto-generated method stub

}

}

This code will help you better understand how to implement different types of providers

Upvotes: 1

Related Questions