2017-07-07 47 views
0

我使用服务获取位置数据,此服务在我的应用在某个活动上运行时启动,并且我需要该活动来请求权限。询问服务内部的位置权限

所以basicly这是我的服务(正常工作)

public class GoogleLocation extends Service implements GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     LocationListener { 

    private static final String TAG = "BOOMBOOMTESTGPS"; 
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 0; 
    private LocationManager mLocationManager = null; 
    private static final int LOCATION_INTERVAL = 0; 
    private static final float LOCATION_DISTANCE = 0f; 
    private int updatePriority; 
    private GoogleApiClient googleApiClient; 
    private LocationRequest locationRequest; 

    private final IBinder mBinder = new LocalBinder(); 
    private Intent intent; 
    private String provider; 
    Context context; 


    Location mLastLocation; 

    public class LocalBinder extends Binder { 
     public GoogleLocation getServerInstance() { 
      return GoogleLocation.this; 
     } 
    } 

    public Location getLocation() { 
     Log.d("IMHERE", "HELLO"); 
     return mLastLocation; 
    } 


    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.e(TAG, "onStartCommand"); 
     context = getApplicationContext(); 
     super.onStartCommand(intent, flags, startId); 
     return START_STICKY; 
    } 


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


    @Override 
    public void onCreate() { 
     Log.e(TAG, "onCreate"); 
     initializeLocationManager(); 

     if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
      this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY; 
     } else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { 
      this.updatePriority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY; 
     } else { 
      this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY; 
     } 

     this.buildGoogleApiClient(); 
     this.createLocationRequest(); 
     this.googleApiClient.connect(); 

    } 

    @Override 
    public void onConnected(@Nullable Bundle bundle) { 
     // Request location updates 
     if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      return; 
     } 
     LocationServices.FusedLocationApi.requestLocationUpdates(this.googleApiClient, this.locationRequest,this); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

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

    } 

    @Override 
    public void onLocationChanged(Location location) { 
     mLastLocation = location; 
     Log.d("localizacao",mLastLocation.toString()); 
    } 


    @Override 
    public void onDestroy() { 
     Log.e(TAG, "onDestroy"); 
     super.onDestroy(); 

     this.googleApiClient.unregisterConnectionCallbacks(this); 
     this.googleApiClient.unregisterConnectionFailedListener(this); 
     this.googleApiClient.disconnect(); 
     this.mLastLocation = null; 
    } 



    private void initializeLocationManager() { 
     Log.e(TAG, "initializeLocationManager"); 
     mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
     if (mLocationManager == null) { 
      mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); 
     } 
    } 

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

    private void createLocationRequest() { 
     this.locationRequest = new LocationRequest(); 
     this.locationRequest.setInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); 
     this.locationRequest.setPriority(updatePriority); 

    } 

这里是我开始它

package com.example.afcosta.inesctec.pt.android; 

import android.Manifest; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.support.annotation.NonNull; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 

import com.example.afcosta.inesctec.pt.android.services.GoogleLocation; 

public class LocationPermission extends AppCompatActivity { 

    public static final int REQ_PERMISSION = 99; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     askPermission(); 
     Intent i = new Intent(this,Login.class); 
     startActivity(i); 
    } 

    // PEDIDO DE PERMISSÃO 
    private void askPermission() { 
     checkLocationPermission(); 
    } 

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 

    public boolean checkLocationPermission() { 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission. ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      // Should we show an explanation? 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        Manifest.permission. ACCESS_FINE_LOCATION)) { 

       // Show an explanation to the user *asynchronously* -- don't block 
       // this thread waiting for the user's response! After the user 
       // sees the explanation, try again to request the permission. 
       new AlertDialog.Builder(this) 
         .setTitle("Partilhar localização") 
         .setMessage("Permitir a partilha de dados sobre a sua localização?") 
         .setPositiveButton("ok", new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialogInterface, int i) { 
           //Prompt the user once explanation has been shown 
           ActivityCompat.requestPermissions(LocationPermission.this, 
             new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
             MY_PERMISSIONS_REQUEST_LOCATION); 
          } 
         }) 
         .create() 
         .show(); 


      } else { 
       // No explanation needed, we can request the permission. 
       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission. ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } 
      return false; 
     } else { 
      startService(new Intent(this, GoogleLocation.class)); 
      return true; 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_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 
        // location-related task you need to do. 
        if (ContextCompat.checkSelfPermission(this, 
          Manifest.permission. ACCESS_FINE_LOCATION) 
          == PackageManager.PERMISSION_GRANTED) { 

         startService(new Intent(this, GoogleLocation.class)); 
        } 

       } else { 

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

       } 
       return; 
      } 

     } 
    } 
} 

的事情是,我需要问权限时他第一次运行该应用程序,或者他已禁用该位置。那从来没有发生过。

我应该在用户授予许可时开始服务。

对此有何帮助?

感谢

+1

请求允许应该发生在开始服务之前 – tyczj

回答

0

你可以通过这种方式要求任何允许在运行时:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) { 

    } else { 
     ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RC_ACCESS_FINE_LOCATION); 
    } 
} 

,你可以得到它的结果:

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

     } 
    } 
} 
0
@Override 
    protected Boolean processInBackground(Void... params) { 
     PermissionResponse response = PermissionEverywhere.getPermission(getApplicationContext(), 
     new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
       REQ_CODE, 
       "Notification title", 
       "This app need external permisison", 
       R.launcher) 
       .call(); 

     boolean isGranted = response.isGranted(); 

     if(isGrante){ 


     // here do your stuff 
     } 
    }