【问题标题】:Checking if permission is available for GPS_PROVIDER检查权限是否可用于 GPS_PROVIDER
【发布时间】:2016-05-04 19:30:31
【问题描述】:

定义位置后,我得到红色下划线,上面写着:“调用需要权限,可能会被用户拒绝:代码应明确检查权限是否可用(使用'checkPermission')或处理潜在的'SecurityException '

我该如何解决这个问题?

public class map extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private FloatingActionButton plus;
LocationManager lm;
Location location;
double latitude, longitude;

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

    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location==null){
        //Location wasnt gathered
    }else{
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    }



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

    plus = (FloatingActionButton) findViewById(R.id.newPlace);

    plus.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            startActivity(new Intent(map.this, newPlacePop.class));
        }
    });
}

【问题讨论】:

标签: android permissions location


【解决方案1】:

您是否向 AndroidManifest 添加了适当的权限?即:

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

你也可以把你的电话包装在一个

LocationManager enabledManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (enabledManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
    location = enabledManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location==null){
         //Location wasnt gathered
    }else{
         latitude = location.getLatitude();
         longitude = location.getLongitude();
    }
}

如果你同时做这两个你应该没问题。

【讨论】:

  • 完美运行!谢谢
【解决方案2】:

在您的 Android 清单中添加以下权限之一作为子项。许可证常用位置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >
...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >
...
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
...
</manifest>

我建议阅读初始文档

location google

【讨论】:

  • 这也是你的兴趣link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 1970-01-01
  • 2021-07-25
  • 2021-03-02
相关资源
最近更新 更多