在Android Marshmallow中使用gps提供程序时,位置管理器返回null位置

时间:2016-08-22 09:11:34

标签: android location reverse-geocoding

我编码检测我在android marshmallow中的当前位置,但我得到null位置。请告诉任何解决方案来解决这个问题。谷歌地图正在我的手机中工作,所以为什么它返回null。

MainActivity.class

if (isGPSEnabled) {
    if (location == null) {
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        if (mLocationManager != null) {
            // mLocationManager.removeUpdates(locationListener);
            location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Log.i("location","location-->"+location);
            tv_new.setText("Location:" +String.valueOf(location));

            if (location != null) {

                latitude = location.getLatitude();
                longitude = location.getLongitude();
                tv_lat.setText("Latitude:" + String.valueOf(latitude));
                tv_lon.setText("Longitude:" +String.valueOf(longitude));
                String filterAddress = "";

                try {
                    Log.i("TAG", "geoCoder" + geoCoder);
                    List<Address> addresses = geoCoder.getFromLocation(latitude, longitude, 1);
                        Log.i("TAG", "addresses" + addresses.size()+latitude+longitude);
                        for (int i = 0; i < addresses.get(0)
                                .getMaxAddressLineIndex(); i++) {
                            filterAddress += addresses.get(0).getAddressLine(i)
                                    + " ";
                            Log.i("TAG", "filterAddress" + filterAddress);
                            tv_address.setText("Address"+ filterAddress);
                         }

                } 
                catch (IOException ex) {
                    Log.i("TAG", "filterAddress catch 1st"+ ex+ filterAddress);
                    ex.printStackTrace();

                } catch (Exception e2) {
                    Log.i("TAG", "filterAddress catch 2nd"+e2+"--->"+geoCoder);

                    // TODO: handle exception
                    e2.printStackTrace();
                }
            }
        }
    }
}

输出

Location:null in ASUS_ZOOLD Phone

2 个答案:

答案 0 :(得分:1)

试试这样..

public class Splash extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> {

    /** Define all global variables over here */
    Context context;
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

    // All GPS based work goes over here ..
    protected static final String TAG = "UserNavigation";
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;
    public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    protected GoogleApiClient mGoogleApiClient;
    protected LocationRequest mLocationRequest;
    protected LocationSettingsRequest mLocationSettingsRequest;
    protected Location mCurrentLocation;
    protected Boolean mRequestingLocationUpdates = false;
    protected String mLastUpdateTime;
    private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1;

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

        context = Splash.this;
        SharedPrefUtil.setSharedPref(context, "alert", false);
        new TestAsync().execute();

        initui();

        PulsatorLayout pulsator = (PulsatorLayout) findViewById(R.id.pulsator);
        pulsator.start();

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED)
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE}, PERMISSION_ACCESS_COARSE_LOCATION);
            else
                checkLocationSettings();
        }
        else
            checkLocationSettings();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_ACCESS_COARSE_LOCATION:

                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)
                    checkLocationSettings();
                else
                    finish();

                break;
        }
    }

    private void initui() {
        initiateSplashWork();
    }

    private void initiateSplashWork() {
        if (checkPlayServices()) {
            initiateGPS();
        }
    }

    private void initiateGPS()
    {
        buildGoogleApiClient();
        createLocationRequest();
        buildLocationSettingsRequest();
    }

    private boolean checkPlayServices() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                        .show();
            } else {
                Toast.makeText(context, R.string.toast_device_not_support, Toast.LENGTH_SHORT).show();
                finish();
            }
            return false;
        }
        return true;
    }

    /** All GPS based method callback  */
    @Override
    public void onConnected(Bundle bundle) {

        Thread logoTimer = new Thread() {
            public void run() {
                try {
                    int logoTimer = 0;
                    while (logoTimer < 5000) {
                        sleep(100);
                        logoTimer = logoTimer + 100;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        logoTimer.start();

        if (mCurrentLocation == null)
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                {
                    mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());

                    return;
                }
                else
                {
                    mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
                }
            }
            else
            {
                mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
            }
        }
    }

    private void initiateNext()
    {
        Thread logoTimer = new Thread() {
            public void run()
            {
                try
                {
                    int logoTimer = 0;
                    while (logoTimer < 5000) {
                        sleep(100);
                        logoTimer = logoTimer + 100;
                    }
                    Intent intent = new Intent(context, OneClassBuilt.class);
                    startActivity(intent);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    finish();
                }
            }
        };
        logoTimer.start();
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    }

    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        Toast.makeText(context, "onLocationChanged method : " + location.getLatitude() + " ____ " + location.getLongitude(), Toast.LENGTH_SHORT).show();
        SharedPrefUtil.setSharedPref(context, "lat", String.valueOf(location.getLatitude()));
        SharedPrefUtil.setSharedPref(context, "lon", String.valueOf(location.getLongitude()));
    }

    protected synchronized void buildGoogleApiClient() {
        Log.i(TAG, "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    protected void buildLocationSettingsRequest() {
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true);
        mLocationSettingsRequest = builder.build();
    }

    protected void checkLocationSettings() {
        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, mLocationSettingsRequest);
        result.setResultCallback(this);
    }

    @Override
    public void onResult(LocationSettingsResult locationSettingsResult) {
        final Status status = locationSettingsResult.getStatus();

        switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                Log.i(TAG, "All location settings are satisfied.");
                startLocationUpdates();
                initiateNext();
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" + "upgrade location settings ");

                try {
                    status.startResolutionForResult(Splash.this, REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException e) {
                    Log.i(TAG, "PendingIntent unable to execute request.");
                }
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                finish();
                Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + "not created.");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        Log.i(TAG, "User agreed to make required location settings changes.");
                        startLocationUpdates();
                        initiateNext();
                        break;
                    case Activity.RESULT_CANCELED:
                        Log.i(TAG, "User chose not to make required location settings changes.");
                        finish();
                        break;
                }
                break;
        }
    }

    protected void startLocationUpdates() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                mRequestingLocationUpdates = true;
            }
        });
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                mRequestingLocationUpdates = false;
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null)
            mGoogleApiClient.connect();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected() && mRequestingLocationUpdates)
            startLocationUpdates();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
            stopLocationUpdates();
    }

    @Override
    protected void onStop() {
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
        super.onStop();
    }
} // End of main class over here ..

在清单中:

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

在App gradle文件中依赖add ..

compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.google.android.gms:play-services-location:8.1.0'

答案 1 :(得分:0)

添加此代码以请求许可

`

private void checkForPermisson {
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 202);
        }
        return;
    } else {
      //add your if block here
  }


}


   @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {      
        switch (requestCode) {
            case 202:
   if (grantResults.length > 0 && grantResults[0] ==    PackageManager.PERMISSION_GRANTED) {
              //add your if block here
            } else {
                Log.e(TAG, "else RequestPermission");
            }
                break;
            default:
                return;
        }       
}

`