1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Android java Location updates are not running

Discussion in 'Programming' started by carlosx2, May 21, 2016.

  1. #1
    I am trying to build an app that tracks the route some one is running. I am using google api for this and it is working good also adding polylines to the map is working as it should but i am not getting any location updates for some reason. I have been on this for a week now and i need some extra help.

    *************************************

    import android.app.AlertDialog;

    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.IntentSender;
    import android.content.SharedPreferences;
    import android.content.pm.PackageManager;
    import android.graphics.Color;


    import android.location.Criteria;
    import android.location.Location;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.content.ContextCompat;
    import android.support.v4.widget.DrawerLayout;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLng;

    import com.google.android.gms.maps.CameraUpdate;

    import com.google.android.gms.maps.MapView;
    import com.google.android.gms.maps.MapsInitializer;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.model.PolylineOptions;
    import com.squareup.picasso.Picasso;

    import java.math.BigDecimal;
    import java.util.ArrayList;

    /** * Created by gebruiker on 19-05-16. */public class WorkoutActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {


    private static String TAG = WorkoutActivity.class.getSimpleName();

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    LocationRequest mLocationRequest;

    MapView mapView;
    GoogleMap map;
    private GoogleApiClient mGoogleApiClient;

    private SharedPreferences preferenceSettings;
    private SharedPreferences.Editor preferenceEditor;
    private static final int PREFERENCE_MODE_PRIVATE = 0;
    private static final String PREF_NAME = "UserDetails";

    public static final String POST_USEREMAIL = "username";

    MainActivity mainactivity;

    String emailUser, workoutType, provider;

    Button stopWorkout, startWorkout;

    TextView speed, info;

    ImageView workoutImage;

    LinearLayout mapLayout, startWorkoutLayout;

    Double currentLat, currentLong;

    Double Lat, Longi;
    String latLong = "No Location Found!!!";
    protected LocationManager locationManager;

    final private int REQUEST_CODE_ASK_PERMISSIONS = 123;

    //counter that is incremented every time a new position is received, used to calculate average speedint counter = 0;

    //objects to store values for current and average speedprotected double currentSpeed;
    protected double kmphSpeed;
    protected double avgSpeed;
    protected double avgKmph;
    protected double totalSpeed;
    protected double totalKmph;

    ArrayList<LatLng> polylines;



    @Overridepublic void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



    preferenceSettings = this.getActivity().getSharedPreferences(PREF_NAME, PREFERENCE_MODE_PRIVATE);
    preferenceEditor = preferenceSettings.edit();
    emailUser = preferenceSettings.getString("Email", null);

    Log.d("Saved user email:", "" + emailUser);

    Bundle bundle = this.getArguments();
    if (bundle != null) {

    workoutType = bundle.getString("workoutType");

    }


    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .build();

    // Create the LocationRequest objectmLocationRequest = LocationRequest.create()
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    .setInterval(1 * 1000) // 5 seconds, in milliseconds.setFastestInterval(1 * 1000); // 1 second, in milliseconds}



    @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_workout, container, false);

    mapView = (MapView) view.findViewById(R.id.mapview);
    stopWorkout = (Button) view.findViewById(R.id.stopWorkout);
    startWorkout = (Button) view.findViewById(R.id.startWorkout);
    startWorkoutLayout = (LinearLayout) view.findViewById(R.id.startWorkoutLayout);
    mapLayout = (LinearLayout) view.findViewById(R.id.mapLayout);
    workoutImage = (ImageView) view.findViewById(R.id.workoutImage);

    speed = (TextView) view.findViewById(R.id.speed);
    info = (TextView) view.findViewById(R.id.info);

    mapView.onCreate(savedInstanceState);

    mainactivity = (MainActivity )getActivity();

    mainactivity.menuButton.setVisibility(View.GONE);
    mainactivity.mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    mainactivity.pageTitle.setText("Workout");

    mapLayout.setVisibility(View.GONE);

    polylines = new ArrayList<LatLng>();

    // Gets to GoogleMap from the MapView and does initialization stuffmap = mapView.getMap();
    map.getUiSettings().setMyLocationButtonEnabled(false);
    map.setMyLocationEnabled(true);

    // Needs to call MapsInitializer before doing any CameraUpdateFactory callsMapsInitializer.initialize(this.getActivity());


    stopWorkout.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    selectOption();
    }
    });

    workoutType = "walking";

    startWorkout.setOnClickListener(new View.OnClickListener() {

    @Overridepublic void onClick(View v) {

    mapLayout.setVisibility(View.VISIBLE);
    startWorkoutLayout.setVisibility(View.GONE);
    }
    });

    if(workoutType.matches("running")){

    Picasso.with(this.getActivity())
    .load(R.drawable.newrun)
    .fit()
    .centerCrop()
    .into(workoutImage);
    }

    if(workoutType.matches("cycling")){

    Picasso.with(this.getActivity())
    .load(R.drawable.newcycling)
    .fit()
    .centerCrop()
    .into(workoutImage);
    }

    if(workoutType.matches("walking")){

    Picasso.with(this.getActivity())
    .load(R.drawable.newwalk)
    .fit()
    .centerCrop()
    .into(workoutImage);
    }



    return view;

    }

    @Overridepublic void onDestroy() {
    super.onDestroy();

    mainactivity.mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

    if (mGoogleApiClient.isConnected()) {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    mGoogleApiClient.disconnect();
    }

    }

    @Overridepublic void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
    }

    @Overridepublic void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    mapView.onResume();
    mGoogleApiClient.connect();
    }

    @Overridepublic void onPause() {
    super.onPause();
    if (mGoogleApiClient.isConnected()) {
    mGoogleApiClient.disconnect();
    }
    }

    @Overridepublic void onMapReady(GoogleMap googleMap) {
    //DO WHATEVER YOU WANT WITH GOOGLEMAPmap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    map.setMyLocationEnabled(false);
    map.setTrafficEnabled(false);
    map.setIndoorEnabled(true);
    map.setBuildingsEnabled(true);
    map.getUiSettings().setZoomControlsEnabled(true);
    }


    @Overridepublic void onLocationChanged(Location location) {
    // TODO Auto-generated method stubLog.d(TAG, "Location update running");

    handleNewLocation(location);

    }



    public void selectOption() {
    final CharSequence[] items = { "Workout Opslaan", "Afbreken", "Sluiten" };
    AlertDialog.Builder builder = new AlertDialog.Builder(WorkoutActivity.this.getActivity());
    builder.setTitle("Workout opties");
    builder.setItems(items, new DialogInterface.OnClickListener() {
    @Overridepublic void onClick(DialogInterface dialog, int item) {
    if (items[item].equals("Workout Opslaan")) {

    } else if (items[item].equals("Afbreken")) {

    mapView.onDestroy();
    mainactivity.mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

    mainactivity.menuButton.setVisibility(View.VISIBLE);

    if (mGoogleApiClient.isConnected()) {
    onDestroy();
    }

    Fragment fragment = new HomePage();
    // Insert the fragment by replacing any existing fragmentFragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
    .replace(R.id.mainContent, fragment)
    .commit();

    } else if (items[item].equals("Sluiten")) {
    dialog.dismiss();
    }
    }
    });
    builder.show();
    }



    @Overridepublic void onConnected(@Nullable Bundle bundle) {

    Log.i(TAG, "Location services connected.");

    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (location == null) {

    Log.i(TAG, "Location connecting.");

    if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
    == PackageManager.PERMISSION_GRANTED) {

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    }else {
    requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 0);

    }
    }
    else {

    Log.i(TAG, "Running new location update");

    handleNewLocation(location);
    };


    }



    @Overridepublic void onConnectionSuspended(int i) {

    Log.i(TAG, "Location services suspended. Please reconnect.");
    }

    @Overridepublic void onConnectionFailed(ConnectionResult connectionResult) {
    if (connectionResult.hasResolution()) {
    try {
    // Start an Activity that tries to resolve the errorconnectionResult.startResolutionForResult(this.getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
    } catch (IntentSender.SendIntentException e) {
    e.printStackTrace();
    }
    } else {
    Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
    }


    private void handleNewLocation(Location location) {

    Log.d(TAG, location.toString());

    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();

    Lat = location.getLatitude();
    Longi = location.getLongitude();

    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

    CameraUpdate zoom=CameraUpdateFactory.zoomTo(17);

    map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    map.animateCamera(zoom);

    counter++;

    //current speed of the gps devicecurrentSpeed = round(location.getSpeed(),3, BigDecimal.ROUND_HALF_UP);
    kmphSpeed = round((currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);

    //all speeds added togethertotalSpeed = totalSpeed + currentSpeed;
    totalKmph = totalKmph + kmphSpeed;

    //calculates average speedavgSpeed = round(totalSpeed/counter,3,BigDecimal.ROUND_HALF_UP);
    avgKmph = round(totalKmph/counter,3,BigDecimal.ROUND_HALF_UP);

    //gets positioncurrentLatitude = round(((double) (location.getLatitude())),3,BigDecimal.ROUND_HALF_UP);
    currentLongitude = round(((double) (location.getLongitude())),3,BigDecimal.ROUND_HALF_UP);


    String infoDetails = "Afstand: "+" | Tijd: ";
    String updateSpeed = String.valueOf(kmphSpeed);

    Log.d(TAG, updateSpeed.toString());

    //info.setText();speed.setText("Snelheid: "+updateSpeed+" km/hr");

    buildPolyline();

    }



    //Method to round the doubles to a max of 3 decimal placespublic static double round(double unrounded, int precision, int roundingMode)
    {
    BigDecimal bd = new BigDecimal(unrounded);
    BigDecimal rounded = bd.setScale(precision, roundingMode);
    return rounded.doubleValue();
    }



    public void buildPolyline(){

    Log.d(TAG,"Adding polyline" );


    LatLng polyline;


    polyline = new LatLng(Lat, Longi);

    polylines.add(polyline);

    Log.d("Locations Array", ""+polylines);

    map.addPolyline(new PolylineOptions().addAll(polylines).width(6.0f).color(Color.BLUE));

    //map.moveCamera(CameraUpdateFactory.newLatLngZoom(Start, 14));}

    private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.if (map == null) {
    // Try to obtain the map from the SupportMapFragment.map = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapview))
    .getMap();
    // Check if we were successful in obtaining the map.if (map != null) {

    }
    }
    }
    }
    ******************************************

    I have a location manager but it seems it is just not running. I only get a new update then i dismiss the app and turn it back on.

    I hope someone can help me with this, i am really stuck.
     
    carlosx2, May 21, 2016 IP