Android GoogleMaps myLocation权限

Android GoogleMaps myLocation权限,第1张

概述使用最新版本的Android…您应该先检查用户是否已授予您权限,然后再使用其位置信息.我已经阅读了androiddocs,这是我想出的代码.我正在检查用户是否已被授予权限,如果尚未授予用户…则我们询问,然后结果上有一个回调函数,依此类推.我已经遍历了很多次代码,并且除了似乎一切正常

使用最新版本的Android …您应该先检查用户是否已授予您权限,然后再使用其位置信息.我已经阅读了androID docs,这是我想出的代码.

我正在检查用户是否已被授予权限,如果尚未授予用户…则我们询问,然后结果上有一个回调函数,依此类推.

我已经遍历了很多次代码,并且除了似乎一切正常之外:当我终于尝试使用fusedLocationAPI.getLastLocation以编程方式获取用户的位置时……它返回NulL!

我已经重新上传了我拥有的代码.

任何可以弄清楚这一点并且对我真正有用的人,您可以得到我所有的代表分数…

package com.example.greg.rightNow;import androID.content.pm.PackageManager;import androID.location.Location;import androID.support.annotation.NonNull;import androID.support.annotation.Nullable;import androID.support.v4.app.ActivityCompat;import androID.support.v4.app.FragmentActivity;import androID.os.Bundle;import androID.support.v4.content.ContextCompat;import androID.Manifest;import com.Google.androID.gms.common.ConnectionResult;import com.Google.androID.gms.common.API.API;import com.Google.androID.gms.common.API.Googleapiclient.ConnectionCallbacks;import com.Google.androID.gms.common.API.Googleapiclient;import com.Google.androID.gms.common.API.PendingResult;import com.Google.androID.gms.common.API.Status;import com.Google.androID.gms.drive.Drive;import com.Google.androID.gms.location.LocationServices;import com.Google.androID.gms.maps.CameraUpdateFactory;import com.Google.androID.gms.maps.GoogleMap;import com.Google.androID.gms.maps.OnMapReadyCallback;import com.Google.androID.gms.maps.SupportMapFragment;import com.Google.androID.gms.maps.model.LatLng;import com.Google.androID.gms.maps.model.MarkerOptions;import com.Google.androID.gms.plus.Plus;import java.io.fileDescriptor;import java.io.PrintWriter;import java.util.concurrent.TimeUnit;public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks {    private Googleapiclient mGoogleapiclient;    private GoogleMap mMap;    private Location mLastLocation;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_maps);        // Obtain the SupportMapFragment and get notifIEd when the map is ready to be used.        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()                .findFragmentByID(R.ID.map);        mapFragment.getMapAsync(this);        // Create an instance of Googleapiclient.        mGoogleapiclient = new Googleapiclient.Builder(this)                .addAPI(Drive.API)                .addAPI(Plus.API)                .addScope(Drive.ScopE_file)                .addConnectionCallbacks(this)        //        .addOnConnectionFailedListener(this)                .addAPI(LocationServices.API)                .build();    }    @OverrIDe    public voID onConnected(@Nullable Bundle bundle) {        }    protected voID onStart() {        mGoogleapiclient.connect();        super.onStart();    }    protected voID onStop() {        mGoogleapiclient.disconnect();        super.onStop();    }    /**     * Manipulates the map once available.     * This callback is triggered when the map is ready to be used.     * This is where we can add markers or lines, add Listeners or move the camera. In this case,     * we just add a marker near Sydney, Australia.     * If Google Play services is not installed on the device, the user will be prompted to install     * it insIDe the SupportMapFragment. This method will only be triggered once the user has     * installed Google Play services and returned to the app.     * Manifest.permission.ACCESS_FINE_LOCATION     */    @OverrIDe    public voID onRequestPermissionsResult(int requestCode,                                           String permissions[], int[] grantResults) {        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == grantResults[0]) {            mMap.setMyLocationEnabled(true);        }        mLastLocation = LocationServices.FusedLocationAPI.getLastLocation(mGoogleapiclient);        LatLng myLat = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());        // Add a marker in Sydney and move the camera        LatLng sydney = new LatLng(-34, 151);        mMap.addMarker(new MarkerOptions().position(sydney).Title("Marker in Sydney"));        mMap.moveCamera(CameraUpdateFactory.newLatLng(myLat));    }    @OverrIDe    public voID onMapReady(GoogleMap GoogleMap) {        mMap = GoogleMap;        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)                == 0) {            ActivityCompat.requestPermissions(this,                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);        }        else if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) ==-1) {            mLastLocation = LocationServices.FusedLocationAPI.getLastLocation(mGoogleapiclient);            LatLng myLat = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());            // Add a marker in Sydney and move the camera            LatLng sydney = new LatLng(-34, 151);            mMap.addMarker(new MarkerOptions().position(sydney).Title("Marker in Sydney"));            mMap.moveCamera(CameraUpdateFactory.newLatLng(myLat));        }    }    @OverrIDe    public voID onConnectionSuspended(int i) {    }}

您会注意到,我不得不对此行进行注释:

 //   .addOnConnectionFailedListener(this)

如果我取消注释…,则“ this”用红色下划线,并且收到错误消息,指出“ …在Builder中无法应用于com.example.greg.MapsActivity等”

解决方法:

使用ContextCompat.checkSelfPermission检查权限后,如果未授予权限,则可以请求该权限.从the documentation开始:

另外,使用Googleapiclient(documentation)时,您需要处理连接失败的问题.在您的代码中,连接失败,您没有在onConnectionFailed上对其进行管理.

最后,我从您的代码中删除了以下内容(这导致连接失败,不需要使用LocationServices并获取最后的位置):

.addAPI(Drive.API).addAPI(Plus.API).addScope(Drive.ScopE_file)

这是一个工作示例:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, Googleapiclient.ConnectionCallbacks, Googleapiclient.OnConnectionFailedListener {    private static final int FINE_LOCATION_PERMISSION_REQUEST = 1;    private static final int CONNECTION_RESolUTION_REQUEST = 2;    private Googleapiclient mGoogleapiclient;    private GoogleMap mMap;    private Location mLastLocation;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_maps);        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()                .findFragmentByID(R.ID.map);        mapFragment.getMapAsync(this);        buildGoogleapiclient();    }    @OverrIDe    protected voID onResume() {        super.onResume();        buildGoogleapiclient();    }    private voID buildGoogleapiclient() {        if (mGoogleapiclient == null) {            mGoogleapiclient = new Googleapiclient.Builder(this)                    .addConnectionCallbacks(this)                    .addOnConnectionFailedListener(this)                    .addAPI(LocationServices.API)                    .build();        }    }    @OverrIDe    public voID onConnected(@Nullable Bundle bundle) {        findLocation();    }    protected voID onStart() {        mGoogleapiclient.connect();        super.onStart();    }    protected voID onStop() {        mGoogleapiclient.disconnect();        super.onStop();    }    @OverrIDe    public voID onMapReady(GoogleMap GoogleMap) {        mMap = GoogleMap;    }    @OverrIDe    public voID onConnectionSuspended(int i) {        Toast.makeText(this, "Connection suspended", Toast.LENGTH_SHORT).show();    }    @OverrIDe    public voID onConnectionFailed(@NonNull final ConnectionResult connectionResult) {        if (connectionResult.hasResolution()) {            try {                connectionResult.startResolutionForResult(this, CONNECTION_RESolUTION_REQUEST);            } catch (IntentSender.SendIntentException e) {                // There was an error with the resolution intent. Try again.                mGoogleapiclient.connect();            }        } else {            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this, 1);            dialog.show();        }    }    @OverrIDe    protected voID onActivityResult(int requestCode, int resultCode,                                    Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (requestCode == CONNECTION_RESolUTION_REQUEST && resultCode == RESulT_OK) {            mGoogleapiclient.connect();        }    }    private voID findLocation() {        if (ContextCompat.checkSelfPermission(this,                Manifest.permission.ACCESS_FINE_LOCATION)                != PackageManager.PERMISSION_GRANTED) {            ActivityCompat.requestPermissions(this,                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},                    FINE_LOCATION_PERMISSION_REQUEST);        } else {            mLastLocation = LocationServices.FusedLocationAPI.getLastLocation(mGoogleapiclient);            LatLng myLat = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());            // Add a marker in Sydney and move the camera            LatLng sydney = new LatLng(-34, 151);            mMap.addMarker(new MarkerOptions().position(sydney).Title("Marker in Sydney"));            mMap.moveCamera(CameraUpdateFactory.newLatLng(myLat));        }    }    @OverrIDe    public voID onRequestPermissionsResult(int requestCode,                                           String permissions[], int[] grantResults) {        switch (requestCode) {            case FINE_LOCATION_PERMISSION_REQUEST: {                if (grantResults.length > 0                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                    findLocation();                }            }        }    }}
总结

以上是内存溢出为你收集整理的Android GoogleMaps myLocation权限全部内容,希望文章能够帮你解决Android GoogleMaps myLocation权限所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1095095.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存