询问服务

时间:2017-07-07 18:20:10

标签: java android google-maps location fusedlocationproviderapi

我使用服务获取位置数据,当我的应用程序在某个活动上运行时启动此服务,我需要该活动来请求权限。

基本上这是我的服务(工作正常)

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;
            }

        }
    }
}

问题是,我第一次运行应用程序时需要请求权限,或者他已禁用该位置。而这种情况从未发生过。

我应该在用户授予权限时启动该服务。

对此有何帮助?

由于

2 个答案:

答案 0 :(得分: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: {

        }
    }
}

答案 1 :(得分:0)

keepfile