如何在 Android Studio 中请求位置权限?

Posted

技术标签:

【中文标题】如何在 Android Studio 中请求位置权限?【英文标题】:How to ask for location permission in Android Studio? 【发布时间】:2019-11-27 15:29:13 【问题描述】:

我尝试了很多代码和解决方案,但都没有奏效。我想请求用户许可并获得弹出窗口。即使我使用了代码,窗口也不会显示?我认为代码可以更改,但我不知道确切的位置。另外,我是 android Studio 新手



public class MainActivity extends AppCompatActivity implements OnMapReadyCallback 


    private GoogleMap mMap;
    private LatLngBounds PODGORICA = new LatLngBounds(
            new LatLng(42.400334, 19.227705), new LatLng(42.470269, 19.323107));

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;


    private static final String TAG = "MapActivity";

    LocationManager locationManager;
    String provider;


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


        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);

        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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


        Button btnQR = (Button) findViewById(R.id.skener);


        btnQR.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                startActivity(intent);
            
        );

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
                requestPermissions(new String[]Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET
                        ,10);
            
            return;
        


    


    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
        if (mToggle.onOptionsItemSelected(item)) 
            return true;
        
        return super.onOptionsItemSelected(item);
    


    @Override
    public void onMapReady(GoogleMap googleMap) 


        mMap = googleMap;

        mMap.setLatLngBoundsForCameraTarget(PODGORICA);
        mMap.setMinZoomPreference(5.0f);
        mMap.setMaxZoomPreference(25.0f);

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(42.441332, 19.262953))
                .zoom(15)
                .bearing(0)
                //.tilt(45)
                .build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));



     //   mMap.setMyLocationEnabled(true);

    

我什至尝试了谷歌官方页面的代码,但得到了相同的结果......

【问题讨论】:

检查this 【参考方案1】:

从 API 级别 23(Android 6.0 Marshmallow)开始,我们需要向用户端请求运行时权限。您可以分两步完成。

1) 在AndroidManifest.xml文件中添加这两个权限。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

例子:

<manifest xlmns:android...>
 ...
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
 <application ...
</manifest>

2) 将此代码块放在需要获取当前位置的类中

    if ( Build.VERSION.SDK_INT >= 23)
              if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
                          PackageManager.PERMISSION_GRANTED  )
                   requestPermissions(new String[]
                                      android.Manifest.permission.ACCESS_FINE_LOCATION,
                              REQUEST_CODE_ASK_PERMISSIONS);
                      return ;
                  
              

              getLocation();

  
  //get access to location permission
  final private int REQUEST_CODE_ASK_PERMISSIONS = 123;



  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) 
      switch (requestCode) 
          case REQUEST_CODE_ASK_PERMISSIONS:
              if (grantResults[0] == PackageManager.PERMISSION_GRANTED) 
                  getLocation();
               else 
                  // Permission Denied
                  Toast.makeText( this,"your message" , Toast.LENGTH_SHORT)
                          .show();
              
              break;
          default:
              super.onRequestPermissionsResult(requestCode, permissions, grantResults);
      
  

//Get location
public  void getLocation()
      LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
          Location myLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
              if (myLocation == null) 
              
                  myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

              
  

【讨论】:

【参考方案2】:
if (ContextCompat.checkSelfPermission(thisActivity,
        Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) 

    // Permission is not granted
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.ACCESS_FINE_LOCATION)) 

     else 
        ActivityCompat.requestPermissions(thisActivity,
                new String[]Manifest.permission.ACCESS_COARSE_LOCATION);
    
 else 
    // Permission has already been granted

【讨论】:

这不是新 api 版本的正确解决方案 good edit :) 将在您更改 READ_CONTACTS 后支持您的答案

以上是关于如何在 Android Studio 中请求位置权限?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 android studio 更改 Google 地图中“我的位置”按钮的位置

如何在 Android Studio 中找到方法或变量的使用位置(快捷方式)

如何使用android studio中的改造服务在请求中传递json

如何在 Android Studio 中删除谷歌地图上多个更新位置的旧标记?

在 Android Studio 中使用动画更新标记位置

SDK位置未找到 - Android Studio