2016-05-11 12 views
0

私はユーザのGPS位置にアクセスする必要があるプロジェクトに取り組んでいます。アンドロイド6のため、私は実行時のパーミッションが必要です。私はそれをやろうとしましたが、最初に活動の開始時にgpsの場所を尋ねましたが、私に場所を教えてくれませんでした。私はまだ位置座標を取得していません。誰かが助けることを望む?実行時アクセス許可が動作していません細かい場所Marshmallow

public class benzinpriser_akt extends AppCompatActivity implements OnItemClickListener { 


    public static final int MY_PERMISSION_REQUEST_GPS_LOCATION = 1 ; 
    LocationManager locationManager; 
    LocationListener locationListener; 
    Location currentLocation;  

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
    locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      // Called when a new location is found by the network location provider. 
      currentLocation = location; 
      System.out.println("Current Location "+ currentLocation); 
     } 

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

     public void onProviderEnabled(String provider) { 
     } 

     public void onProviderDisabled(String provider) { 
     } 
    }; 

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



     } else { 


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

    // Some other code regarding listview and fetching data from database 
} 



@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case MY_PERMISSION_REQUEST_GPS_LOCATION: { 
      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

       // permission was granted, yay! Do the 
       // contacts-related task you need to do. 
       System.out.println("Permission Granted"); 
       locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 


      } else { 

       // permission denied, boo! Disable the 
       // functionality that depends on this permission. 
      } 
      return; 
     } 

     // other 'case' lines to check for other 
     // permissions this app might request 
    } 
} 
+0

すでに許可を得ている場合は処理されません。 – Michael

+0

私はコードのどの部分で私がそれを処理できるかを教えてもらえます –

答えて

0

まず第一に、あなたのbuild.gradleにtheeseの2行を追加します。

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

は、その後、あなたの活動に、あなたはそのように実装する必要があります。

public class benzinpriser_akt extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, 
GoogleApiClient.OnConnectionFailedListener,LocationListener, android.location.LocationListener { 
private GoogleApiClient mGoogleApiClient; 
private LocationRequest mLocationRequest; 
private int UPDATE_INTERVAL = 20000; // 20 sec 
private int FASTEST_INTERVAL = 10000; // 10 sec 
private int DISPLACEMENT = 50; // get location per 50 meter change 
protected final String TAG = "Location Service"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(yourlayout); 
//build google api client 
buildGoogleApiClient(); 

    } //oncreate end 
    protected synchronized void buildGoogleApiClient() { 
    Log.v(TAG, "google client building"); 
    if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) { 

     mGoogleApiClient = new GoogleApiClient.Builder(thisService) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API).build(); 
     if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) { 
      mGoogleApiClient.connect(); 
     } 

      startListenLocation(); 

    } else { 
     Log.e(TAG, "unable to connect to google play services."); 
    } 



} 

    public void createLocationRequestWithDialog(final Activity activity){ 

    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
    mLocationRequest.setInterval(UPDATE_INTERVAL); 
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL); 
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
      .addLocationRequest(mLocationRequest); 

    //************************** 
    builder.setAlwaysShow(true); //this is the key ingredient 
    //************************** 
    PendingResult<LocationSettingsResult> result = 
      LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
     @Override 
     public void onResult(LocationSettingsResult result) { 
      final Status status = result.getStatus(); 
      final LocationSettingsStates state = result.getLocationSettingsStates(); 
      switch (status.getStatusCode()) { 
       case LocationSettingsStatusCodes.SUCCESS: 
        // All location settings are satisfied. The client can initialize location 
        // requests here. 
        break; 
       case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
        // Location settings are not satisfied. But could be fixed by showing the user 
        // a dialog. 
        try { 
         // Show the dialog by calling startResolutionForResult(), 
         // and check the result in onActivityResult(). 
         status.startResolutionForResult(
           activity, 1000); 
        } catch (IntentSender.SendIntentException e) { 
         // Ignore the error. 
        } 
        break; 
       case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
        // Location settings are not satisfied. However, we have no way to fix the 
        // settings so we won't show the dialog. 
        break; 
      } 
     } 
    }); 


} 

public void checkGpsPermission(Activity activity) { 
    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 
     ActivityCompat.requestPermissions(activity, 
       new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
       PERMISSION_ACCESS_GPS); 

    } 
    else 
    { 
     createLocationRequestWithDialog(activity); 
    } 


} 

    protected void startListenLocation() { 
    if (ActivityCompat.checkSelfPermission(thisService, Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 
     //no permission , create a notification and want permission 
     NotificationManager notificationManager = (NotificationManager) 
       getSystemService(NOTIFICATION_SERVICE); 
     Notification n = new Notification.Builder(thisService) 
       .setContentTitle(" notification") 
       .setContentText("there is no permission about using gps services, please give location permissions") 
       .setSmallIcon(R.drawable.logo) 
       .setAutoCancel(true) 
       .build(); 
     notificationManager.notify((int)System.currentTimeMillis(), n); 
    } else { 
     // permission has been granted, continue as usual 

    if(mGoogleApiClient.isConnected()) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 

    } 

    } 


} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 

    if (mGoogleApiClient.isConnected() && mLastLocation != null) { 
     createLocationRequestWithDialog(); 
     startListenLocation(); 
    } 
} 
@Override 
public void onConnectionSuspended(int i) { 
    mGoogleApiClient.connect(); 
} 
//TODO add other override methods , onresume, onproviderenabled etc... 

}//class end 

バッテリードレイン:

/* 
    Priority    update interval  Battery drain per hour (%)  Accuracy 
    HIGH_ACCURACY   5 seconds     7.25%     ~10 meters 
    BALANCED_POWER   20 seconds     0.6%     ~40 meters 
    NO_POWER    N/A       small     ~1 mile 

*/

+0

私はそれを試しました、動作していません –

+0

まだ動作していません –

+0

私は前に私が送るコードは、上記のクラスで同じコードを使用することができます。私はプロジェクトの要件のためにGPSの場所が必要ですが、アドバイスのためのthx –

関連する問題