【发布时间】:2018-01-19 06:25:09
【问题描述】:
在这里,我使用“位置管理器”来查找当前位置,并使用“传感器管理器”来获取当前温度。当我使用“位置管理器”时,应用程序崩溃并显示此错误消息:
原因:java.lang.SecurityException:“网络”位置提供程序需要 ACCESS_COARSE_LOCATION 或 ACCESS_FINE_LOCATION 权限。
以下是“位置管理器”和“传感器管理器”的代码
**MainActivity.java**
public class MainActivity extends AppCompatActivity implements SensorEventListener, LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
private SensorManager mSensorManager;
private Sensor mTemperature;
private final static String NOT_SUPPORTED_MESSAGE = "Sorry, sensor not available for this device.";
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_DISTANCE_CHANGE_FOR_UPDATES, MIN_TIME_BW_UPDATES, this);
}
@Override
public void onLocationChanged(Location location) {
locationTextView.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH){
mTemperature= mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); // requires API level 14.
}
if (mTemperature == null) {
temperatureTextView.setText(NOT_SUPPORTED_MESSAGE);
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mTemperature, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
float ambient_temperature = event.values[0];
temperatureTextView.setText(String.valueOf(ambient_temperature) + getResources().getString(R.string.celsius));
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
}
【问题讨论】:
-
您忘记在清单文件中添加权限。只需添加此问题即可解决。
标签: android android-sensors android-location