java.lang.IllegalArgumentException: accuracy=3 whe

2019-07-24 07:49发布

onMapReady seems not to work the way it should in my route tracking activity. In the current version of a route tracking activity that I implemented in java under Android Studio NeueRouteAufzeichnen.java (Neue Route Aufzeichnen -German- means Start recording a new route) I added the following in my onMapReady

if(mLastLocation != null) {
        LatLng myPosition = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
        map.addMarker(new MarkerOptions().position(myPosition).title("myPosition"));
        map.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
    } else{
        LatLng sydney = new LatLng(-34, 151);
        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

to ckeck whether mLastLocation is null. When I move to this activity in my App I see as if Google Maps is about to open a map view then land in an other activity to which I don't refer to in my code. I see neither my current place nor Sydney.

Here is my NeueRouteAufzeichnen.java

package com.noureddine_ouertani.www.wocelli50;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;
import java.util.List;


 public class NeueRouteAufzeichnen extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private LocationManager locationManager;
private Location mLastLocation;
private Location previousLocation;
private long distanceTraveled;

private boolean tracking = false;
private long startTime;
private PowerManager.WakeLock wakeLock;
private boolean gpsFix;

private static final double MILLISECONDS_PER_HOUR = 100 * 60 * 60;
private static final double MILES_PER_KILOMETER = 0.621371192;
private static final int MAP_ZOOM = 18;

private List<Location> locations;


LocationListener mlocationListener;
GoogleMap map;

GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this /* FragmentActivity */,
                this /* OnConnectionFailedListener */)
        .addApi(Drive.API)
        .addScope(Drive.SCOPE_FILE)
        .build();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    setContentView(R.layout.activity_neue_route_aufzeichnen);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    locations = new ArrayList<Location>();
}

protected void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}

protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

@Override
public void onConnected(Bundle connectionHint) {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}

@Override
public void onConnectionSuspended(int i) {

}

public void addPoint(Location location) {
    locations.add(location);
}

@Override
public void onMapReady(GoogleMap map) {

    distanceTraveled = 0;

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_HIGH);
    criteria.setBearingRequired(true);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        float LOCATION_REFRESH_DISTANCE = 1;
        long LOCATION_REFRESH_TIME = 100;
        mlocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                updateLocation(location);
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, mlocationListener);
    }
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NO Sleep");
    wakeLock.acquire();
    if(mLastLocation != null) {
        LatLng myPosition = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
        map.addMarker(new MarkerOptions().position(myPosition).title("myPosition"));
        map.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
    } else{
        LatLng sydney = new LatLng(-34, 151);
        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
    draw();
    tracking = true;
    startTime = System.currentTimeMillis();

}

protected void updateLocation(Location location) {

    if (location != null && gpsFix == true) {
        addPoint(location);

        if (previousLocation != null)
            distanceTraveled += location.distanceTo(previousLocation);
    }
    previousLocation = location;
}

public void draw() {

    if (map == null) {
        return;
    }

    PolylineOptions options = new PolylineOptions();

    options.color(Color.parseColor("#CC0000FF"));
    options.width(5);
    options.visible(true);

    for (Location locRecorded : locations) {
        options.add(new LatLng(locRecorded.getLatitude(),
                locRecorded.getLongitude()));
    }

    map.addPolyline(options);

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

and here is my activity_neue_route_aufzeichnen.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
                  tools:context="com.noureddine_ouertani.www.wocelli50.NeueRouteAufzeichnen">
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map"
    tools:context=".NeueRouteAufzeichnen"
    android:name="com.google.android.gms.maps.SupportMapFragment" />

 </RelativeLayout>

Any hints or help with regard to why my onMapReady doesn't work the way it should?

EDIT : I see the following fatal exception in my logcat when starting this activity from my App:

06-17 19:16:44.980 9859-9859/com.noureddine_ouertani.www.wocelli50 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.noureddine_ouertani.www.wocelli50, PID: 9859 java.lang.IllegalArgumentException: accuracy=3 at android.location.Criteria.setAccuracy(Criteria.java:223) at com.noureddine_ouertani.www.wocelli50.NeueRouteAufzeichnen.onMapReady(NeueRouteAufzeichnen.java:155) at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source) at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source) at android.os.Binder.transact(Binder.java:380) at wv.a(:com.google.android.gms.DynamiteModulesB:82) at maps.ag.t$5.run(Unknown Source) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5538) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

EDIT 2

When I use

ACCURACY_FINE

in criteria.setAccuracy(Criteria.ACCURACY_FINE); or uncomment setAccuracy I get a force close when running as well. My logs say that it happens in line 155

155  else{
156      LatLng sydney = new LatLng(-34, 151);
157        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
158        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));

Here is the log message I got after setting accuracy to fine:

06-17 19:33:27.170 20083-20083/com.noureddine_ouertani.www.wocelli50 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.noureddine_ouertani.www.wocelli50, PID: 20083 java.lang.IllegalArgumentException: accuracy=3 at android.location.Criteria.setAccuracy(Criteria.java:223) at com.noureddine_ouertani.www.wocelli50.NeueRouteAufzeichnen.onMapReady(NeueRouteAufzeichnen.java:155) at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source) at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source) at android.os.Binder.transact(Binder.java:380) at wv.a(:com.google.android.gms.DynamiteModulesB:82) at maps.ag.t$5.run(Unknown Source) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5538) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

the same happens when I use

ACCURACY_COARSE

0条回答
登录 后发表回答