-1

谁能帮我解决问题:

onConnected()方法为什么我

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

代码未执行;并从checkSelfPermission()

我该怎么做才能FusedLocationApi在这段代码中正常工作

我的代码在下面

public class JMSCLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {
    private final String TAG = "MyAwesomeApp";
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    // Check Permissions Now
    private static final int REQUEST_LOCATION = 2;
    //private final double radiusInMeters = 1609.34;
    private final double radiusInMeters = 16.34;
    LatLng firstLatLong;
    Location fLoc;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "GoogleApiClient connection has STARTED");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        firstLatLong = new LatLng(0, 0);
        Log.i(TAG, "GoogleApiClient connection has STARTED");
    }

    @Override
    public void onDestroy() {
        // disconnect the client.
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
            mGoogleApiClient.disconnect();
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Connect the client.
        if (mGoogleApiClient != null && !mGoogleApiClient.isConnected()) {
            mGoogleApiClient.connect();
            Log.i(TAG, "GoogleApiClient mGoogleApiClient.connect();");
        }


        if (mGoogleApiClient.isConnected()) {
            Log.i(TAG, "GoogleApiClient mGoogleApiClient.isConnected();");
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(1000); // Update location every second

        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) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            //return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "GoogleApiClient connection has been suspend");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i(TAG, "GoogleApiClient connection has failed");

    }

    @Override
    public void onLocationChanged(Location mCurrentLocation) {
        Log.i(TAG, "GoogleApiClient Location received: " + mCurrentLocation.toString());
        //test outside
        double mLatitude = mCurrentLocation.getLatitude();
        double mLongitude = mCurrentLocation.getLongitude();
        if(firstLatLong.latitude == 0.0 && firstLatLong.longitude == 0.0){
            firstLatLong = new LatLng(mLatitude,mLongitude);
            fLoc=new Location(mCurrentLocation);
        }
        float[] results = new float[1];
        Location.distanceBetween(firstLatLong.latitude, firstLatLong.longitude,
                mLatitude, mLongitude, results);

        float distanceInMeters = fLoc.distanceTo(mCurrentLocation);
        try{
            if( distanceInMeters > radiusInMeters ){
                Toast.makeText(getBaseContext(), "Outside, distance from center", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getBaseContext(), "Inside, distance from center", Toast.LENGTH_LONG).show();
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }


}
4

2 回答 2

0

您必须请求权限。您只是在检查您的应用是否具有权限。

您忽略了checkSelfPermission()代码中的结果。

阅读评论,它们是不言自明的。

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) {
            // Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            //return;
        } else {
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
}

阅读有关从以下位置请求运行时权限的信息:

  1. https://developer.android.com/training/permissions/requesting.html#perm-request
  2. http://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/

编辑 1

我认为...但是在编译时使用它会给出错误,因为必须使用自检权限,您的意思是 Lint 警告。

@SuppressWarnings("MissingPermission")您可以通过在您正在调用的方法之上添加来抑制它们requestLocationUpdates()

但请确保您requestLocationUpdates()在获得许可的情况下拨打电话(注意if..else块)

于 2016-12-28T13:00:41.733 回答
0

利用:

if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
            REQUEST_ID);
    }else{
        LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}

和:

 @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_ID: {
                for( int i = 0; i < permissions.length; i++ ) {
                    if( grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.d("Permissions", "Permission Granted: " + permissions[i]);
                    } else if( grantResults[i] == PackageManager.PERMISSION_DENIED ) {
                        Log.d( "Permissions", "Permission Denied: " + permissions[i] );
                    }
                }
            }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
于 2016-12-28T13:03:11.060 回答