来自用户的权限已初始化为已授予

时间:2019-10-26 09:33:08

标签: java android

我正在尝试运行下面的代码,以征询用户使用位置服务的许可。 当我运行下面的程序时,屏幕上不会显示Allow "Location Demo" to access this device's location消息(“ Location Demo”是项目的名称)。

public class MainActivity extends AppCompatActivity {

    private LocationManager manager;
    private LocationListener listener;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        manager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.i("Location", location.toString());
            }
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }
            @Override
            public void onProviderEnabled(String provider) {

            }
            @Override
            public void onProviderDisabled(String provider) {

            }
        };
        // Here, if I change the "!=" to "==", the condition holds
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
    }
}

当我将底部的'if'语句从“!=”更改为“ ==”时,上述消息确实出现。因此,我得出的结论是,“ if”中语句的初始值是表明权限实际上是由用户授予的值(甚至在消息启动之前)。 那样行吗?是什么原因造成的? 希望我要问的清楚 预先谢谢你

0 个答案:

没有答案