当前位置: 首页 > 知识库问答 >
问题:

如何在android studio 6.0运行时权限下使用地图活动获取当前位置

康恩
2023-03-14

公共类MapsActivity扩展了FragmentActivity实现了OnMapReadyCallback{

private GoogleMap mMap;
private Location myLocation;
private static final int INITIAL_REQUEST=1337;
private static final int LOCATION_REQUEST=INITIAL_REQUEST+3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    // Get Current Location

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


/**
 * 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.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

   /* // 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(sydney));*/
    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));

    // Enable MyLocation Layer of Google Map
    mMap.setMyLocationEnabled(true);

    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);

    // Get Current Location
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //public void onRequestPermissionsResult(int requestCode, String[] permissions,int[] grantResults)
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST);

        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Location myLocation = locationManager.getLastKnownLocation(provider);

    // set map type
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    // Get latitude of the current location
    double latitude = myLocation.getLatitude();

    // Get longitude of the current location
    double longitude = myLocation.getLongitude();

    // Create a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);

    // Show the current location in Google Map
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the Google Map
    mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
    mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));

}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,int[] grantResults){
    switch (requestCode) {
        case LOCATION_REQUEST: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                doLocationThing();
                // permission was granted, yay! Do the
                // contacts-related task you need to do.


            } else {
                bzzzt();
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
private void doLocationThing() {
    Toast.makeText(this, "Loacation fetched", Toast.LENGTH_SHORT).show();
}
private void bzzzt() {
    Toast.makeText(this, "not found", Toast.LENGTH_LONG).show();
}

}

错误D/AndroidRuntime:正在关闭VM 02-25 16:31:40.313 153 30-15330/com.vivanta.location E/AndroidRuntime:致命异常:main process:com.vivanta.location,PID:15330 java.lang.runtimeException:无法启动活动ComponentInfo{com.vivanta.location/com.vivanta.location.mapsactivity}:java.lang.IllegalArgumentException:只能对Android.app.activitythread.performLaunchActivity(90)在Android.app.activityThread.-Wrap11(activityThread.java),在Android.app.activityThread.h.h.handleMessage(activityThread.java:1354),在Android.os.handler.dispatchMessage(handler.java:102),在Android.os.handler.dispatchMessage(handler.java:148),在Android.app.activityThread.loop(handler.java:148),在Android.app.activityThread.main.internal.os.zygoteinit.main(Zygoteinit.java:618)原因:java.lang.IllegalArgumentException:只能对Android.support.v4.app.fragmentactivity.validaterequestPermissionsRequestCode(fragmentactivity.java:799)在Android.support.v4.app.activityCompatapi23.requestPermissions(activityCompat.java:29)在在Android.app.instrumentation.callactivityoncreate(activity.java:6245)在Android.app.activitythread.performLaunchactivity(activitythread.java:2379)在Android.app.activitythread.handlelaunchactivity(activitythread.java:2490) 在Android.app.activitythread.-Wrap11(activitythread.java.-Wrap11) 在Android.app.activitythread.java:1354), 在loop(looper.jav答:148) 在Android.app.activitythread.main(activitythread.java:5443) 在java.lang.reflect.Method.invoke(原生方法) 在com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:728) 在com.android.internal.os.zygoteinit.main(zygoteinit.java:618) 在com.android.internal.os.zygoteinit.main

共有1个答案

凌嘉志
2023-03-14

runtimePermissionsRequest函数包装整个onmapReady函数,如下所示:

@Override
public void onMapReady(GoogleMap googleMap) {
    if(!runtimePermissionsReqest()){
      // your entire code here.
    }
}


private boolean runtimePermissionsRequest() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
            ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{
                android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
        return true;
    }
    return false;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 100) {
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED &&
                grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            runtimePermissionsRequest();
        }
    }
}
 类似资料:
  • 我试图实现当前位置地图应用程序,我正在加载地图碎片,但它需要纬度和经度值来定位地址...如何实现当前位置地图功能...提前感谢.. 这是我的地图片段。

  • 我做错了什么?

  • 我是android的新手,不知道我做错了什么,这个类得到了经度和纬度并发送到另一个类,代码抛出了一个错误请告诉我该怎么做怎么做: public void onRequestPermissionsResult出错(int requestCode,String[]permissions,int[]grantResults

  • 我正在开发天气应用程序,当应用程序第一次推出时,我想检测用户当前位置,但我尝试使用谷歌地图,但他们要求信用卡,以获得谷歌地图的api密钥,不幸的是,我没有信用卡。你有其他的解决方案或替代方案吗。

  • 问题内容: 我在使用android定位系统的NETWORK提供程序获取当前位置坐标时遇到麻烦。 已经阅读了很多教程,并为我的项目实现了4到5个现有的类,所有这些类都给了我最后的坐标,而不是当前的坐标。 我很确定这个问题是我遗漏的根本问题,但是我无法理解到底是什么。 我现在正在使用的代码: 这是我的主要活动 这是我用于跟踪的课程: 这是我的AndroidManifest.xml 实际上,GPS定位工

  • 问题内容: 嗨,我写了一个应用程序,获取当前的纬度和经度并将其转换为相应的地址。我可以获取纬度和经度,但是如何使用json将其转换为相应的地址。我是json的新手。我尝试了一些示例代码,但没有得到地址 这是我的代码 请帮助我 提前致谢 问题答案: 要改回可读格式,您也可以使用Geocoder,但有时由于Google Play服务问题而无法正常工作。我将这个json地理编码用作第二种选择,以防万一。