【问题标题】:How to get a Location and its Temperature in Android?如何在 Android 中获取位置及其温度?
【发布时间】: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


【解决方案1】:

将此添加到您的 android 清单文件中:

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

并且不要忘记请求位置权限。

【讨论】:

    【解决方案2】:

    您是否询问过运行时权限,并且在设置检查时是否为您的应用启用了位置和传感器。请求运行时权限以使用感觉和位置。

    兼容所有 SDK 版本(android.permission.ACCESS_FINE_LOCATION 在 Android M 中成为危险权限,需要用户手动授予)。

    在 Android M 以下的 Android 版本中,如果您在 AndroidManifest.xml 中添加这些权限,则 ContextCompat.checkSelfPermission(...) 始终返回 true)

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
    
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
    
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle(R.string.title_location_permission)
                        .setMessage(R.string.text_location_permission)
                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MainActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .create()
                        .show();
    
    
            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {
    
                        //Request location updates:
                        locationManager.requestLocationUpdates(provider, 400, 1, this);
                    }
    
                } else {
    
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
    
                }
                return;
            }
        }
    }
    Then call the checkLocationPermission() method in onCreate():
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkLocationPermission();
    }
    

    然后,您可以完全按照问题中的方式使用 onResume() 和 onPause()。这是一个更简洁的精简版:

    @Override
    protected void onResume() {
        super.onResume();
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            locationManager.requestLocationUpdates(provider, 400, 1, this);
        }
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            locationManager.removeUpdates(this);
        }
    }
    

    点击链接了解更多信息 https://developer.android.com/guide/topics/sensors/sensors_overview.html

    【讨论】:

    • 非常感谢。它适用于我的位置,但不适用于温度。请帮我看看房间里的温度。
    猜你喜欢
    • 2011-08-19
    • 2014-12-30
    • 2014-12-25
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    相关资源
    最近更新 更多