当定义了位置时,我得到红色下划线并显示:"呼叫需要权限,可能被用户拒绝:代码应明确检查是否有权限(使用' checkPermission&#39 ;)或处理潜在的' 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));
}
});
}
答案 0 :(得分:0)
您是否已为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();
}
}
如果你同时做这两件事你应该没事。
答案 1 :(得分:0)
添加以下权限之一作为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>
我建议阅读初始文档