美文网首页android
Android获取定位权限,手动打开GPS

Android获取定位权限,手动打开GPS

作者: 图之 | 来源:发表于2018-11-06 11:00 被阅读0次

    获取定位权限,并且在没有打开GPS的时候引导用户打开手机GPS定位。
    超级简单的

      private Button button;
    
        private int GPS_REQUEST_CODE = 1;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            button = findViewById(R.id.open_gps);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    openGPSSEtting();
                }
            });
        }
    
        private boolean checkGpsIsOpen() {
            boolean isOpen;
            LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            return isOpen;
        }
    
        private void openGPSSEtting() {
            if (checkGpsIsOpen()){
                Toast.makeText(this, "true", Toast.LENGTH_SHORT).show();
            }else {
                new AlertDialog.Builder(this).setTitle("open GPS")
                        .setMessage("go to open")
                        //  取消选项
                        .setNegativeButton("cancel",new DialogInterface.OnClickListener(){
    
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Toast.makeText(MainActivity.this, "close", Toast.LENGTH_SHORT).show();
                                // 关闭dialog
                                dialogInterface.dismiss();
                            }
                        })
                        //  确认选项
                        .setPositiveButton("setting", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                              //跳转到手机原生设置页面
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivityForResult(intent,GPS_REQUEST_CODE);
                            }
                        })
                        .setCancelable(false)
                        .show();
            }
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode ==GPS_REQUEST_CODE){
                openGPSSEtting();
            }
        }
    

    相关文章

      网友评论

        本文标题:Android获取定位权限,手动打开GPS

        本文链接:https://www.haomeiwen.com/subject/nedyxqtx.html