2017-09-15 48 views
0

我在我的應用程序中實現fusedLocationAPI。對於具有> =棉花糖的Android手機,我將加入權限。問題是在安裝後第一次,lat和long值返回爲null。但下次啓動應用程序後,它工作正常。下面我張貼我的代碼。請看一看。FusedLocationAPI在添加權限後第一次返回null

裏面的onCreate():

 manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     buildGoogleApiClient(); 
     checkPermission(); 
     if (!mGoogleApiClient.isConnected()) { 
      mGoogleApiClient.connect(); 
     } 
     if (!statusOfGPS) { 
      displayPromptForEnablingGPS(MainActivity.this); 
     } 

其他方法:

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

     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

      return; 
     } 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
      mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
        mGoogleApiClient); 
      if (mLastLocation != null) { 
       lat = mLastLocation.getLatitude(); 
       lon = mLastLocation.getLongitude(); 
       if (!String.valueOf(lat).equals("0.0")){ 
        latitudeVal = mLastLocation.getLatitude(); 
        longitudeVal = mLastLocation.getLongitude(); 
        Log.e("Lat and Lng", String.valueOf(latitudeVal)+ longitudeVal); 
       } 
      } 

     } 

     @Override 
     public void onConnectionSuspended(int i) { 

     } 
     synchronized void buildGoogleApiClient() { 
      mGoogleApiClient = new GoogleApiClient.Builder(this) 
        .addConnectionCallbacks(this) 
        .addOnConnectionFailedListener(this) 
        .addApi(LocationServices.API) 
        .build(); 
     } 

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

     } 
     public void displayPromptForEnablingGPS(final Activity activity) { 
      final android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity); 
      final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS; 
      final String message = "Do you want open GPS setting?"; 
      builder.setMessage(message) 
        .setPositiveButton("OK", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface d, int id) { 
            activity.startActivity(new Intent(action)); 
            d.dismiss(); 
           } 
          }) 
        .setNegativeButton("Cancel", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface d, int id) { 
            d.cancel(); 
           } 
          }); 
      builder.create().show(); 
     } 

    private void requestPermission() { 

     ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
    } 

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) { 
     new AlertDialog.Builder(MainActivity.this) 
       .setMessage(message) 
       .setPositiveButton("OK", okListener) 
       .setNegativeButton("Cancel", null) 
       .create() 
       .show(); 
    } 

    String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }; 


    Activity activity =this; 
    Context context = this; 


    private boolean checkPermission() { 
     int result; 
     List<String> listPermissionsNeeded = new ArrayList<>(); 
     for (String p:permissions) { 
      result = ContextCompat.checkSelfPermission(this,p); 
      if (result != PackageManager.PERMISSION_GRANTED) { 
       listPermissionsNeeded.add(p); 
      } 
     } 
     if (!listPermissionsNeeded.isEmpty()) { 
      ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),10); 

      Log.d("permissionissue","no"); 
      return false; 
     } 
     Log.d("permissionissue","yes"); 
     return true; 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case 101: 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show(); 
        checkPermission(); 
       } else { 
        Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show(); 

        try { 
         Log.d("deniedOnes",permissions[0] + " Denied!!!"); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } 
       break; 
     } 
    } 

回答

0

請使用此代碼:

//對變量聲明

final int MY_REQUEST_CODE=20; 

//方法問permissi在

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 

     if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(AccountSettingActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE); 
     } else if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
      // do your Task here 
     } 
    } else { 
     // do your Task here 

    } 

現在就permissionResult這樣寫:

@Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { 
      // do your Task here 
     } else { 
      Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show(); 
     } 
    } 
0

請儘量使用LocationManager獲得位置更新,如果從FusedLocationProviderClient位置是空的。對於如:

mFusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() { 
     @Override 
     public void onSuccess(Location location) { 

      if (location == null) { 
       startGPS(); 
      } else { 
       startIntentService(location); 
      } 
     } 
    }); 

公共無效startGPS(){

mLocationManager = (LocationManager)SmileMore.appContext.getSystemService(LOCATION_SERVICE); 
    mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener); 
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); 
} 

私人無效initLocationListener(){

mLocationListener = new LocationListener() { 
     @Override 
     public void onLocationChanged(Location location) { 

      if(location == null){ 
       return; 
      } 
      mLocationManager.removeUpdates(this); // remove this listener as soon as you get first location update. 
      startIntentService(location); 
     } 

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

     } 

     @Override 
     public void onProviderEnabled(String provider) { 

     } 

     @Override 
     public void onProviderDisabled(String provider) { 

     } 
    }; 
} 
相關問題