flutter插件开发学习之旅(4)-------检测GPS状态,打开GPS和显示经纬度实战

时间:2024-03-25 20:02:55

检测GPS状态,打开GPS和显示经纬度实战

前言

经过上一篇的学习,大家学习到蓝牙的实战,这节课我们给大家分享Flutter调用原生API实现检测手机GPS状态和打开GPS;再打开GPS之后实现显示当地经纬度

准备工具

这套课程是采用Android Studio进行开发的。当前在此之前请准备好Flutter开发环境,我这里就不进行讲解了

实战开始

lib/main.dart添加一个调用原生方法

 ///////////Flutter 调用原生 Start//////////////

  static const MethodChannel methodChannel=
  MethodChannel('samples.flutter.io/gps');

  Future<void> _inspection()async{
    String message;
    message=await methodChannel.invokeMethod('inspectionGPS');
    setState(() {
      _message=message;
    });
  }

  Future<void> _open()async{
    await methodChannel.invokeMethod('openGPS');
  }

  Future<void> _getDate() async{
    await methodChannel.invokeMethod('getDate');
  }
  //////// Flutter 调用原生  End  ////////

底层原生编写------------接受Flutter调用,调用安卓原生API


  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);


        new MethodChannel(getFlutterView(), BLUETOOTH_CHANNEL).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
                        if (methodCall.method.equals("inspectionGPS")) {
                            boolean isOpen = isOPen();
                            if (isOpen) {		//检测GPS是否开启
                                result.success("GPS已开启");
                            }
                            result.success("GPS未开启");
                        } else if (methodCall.method.equals("openGPS")) {	//打开GPS
                            openGPSSettings(context);
                        } else if (methodCall.method.equals("getDate")) {	//显示经纬度
                            initLocation();
                        }
                    }
                }
        );


    }

检测GPS是否开启

private boolean isOPen() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        /**确认GPS是否开启**/
        if (gps || network) {
            return true;
        }
        return false;
    }

打开GPS

private boolean checkGpsIsOpen() {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return isOpen;
}

private void openGPSSettings(Context context) {
        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, 1);
                        }
                    })
                    .setCancelable(false)
                    .show();
        }
    }

显示经纬度

 @TargetApi(Build.VERSION_CODES.M)
    private void initLocation() {
        //设置间隔两秒获得一次GPS定位信息
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 8, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // 当GPS定位信息发生改变时,更新定位
                localDate=updateShow(location);
                System.out.println("1.返回来的"+localDate);
                final AlertDialog.Builder normalDialog = new AlertDialog.Builder(MainActivity.this);
                normalDialog.setTitle("地区的详细信息");
                normalDialog.setMessage(localDate);
                normalDialog.show();
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @SuppressLint("MissingPermission")
            @Override
            public void onProviderEnabled(String provider) {
                localDate=updateShow(locationManager.getLastKnownLocation(provider));
            }

            @Override
            public void onProviderDisabled(String provider) {
                localDate=updateShow(null);
            }
        });
    }

    //定义一个更新显示的方法
    private String updateShow(Location location) {
        if (location != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("当前的位置信息:\n");
            sb.append("经度:" + location.getLongitude() + "\n");
            sb.append("纬度:" + location.getLatitude() + "\n");
            sb.append("定位精度:" + location.getAccuracy() + "\n");
            System.out.println(sb.toString());
            return sb.toString();
        }
        return null;
    }

下面就是进行简单的布局

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: new Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('GPS状态:'),
                Text(
                  _message
                )
              ],
            ),
            Padding(
              padding: EdgeInsets.all(10.0),
              child: Column(
                children: <Widget>[
                  RaisedButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: Text('检查GPS状态'),
                    onPressed: _inspection,
                  ),
                  RaisedButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: Text('开关GPS'),
                    onPressed: _open,
                  ),
                  RaisedButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: Text('获取经纬度'),
                    onPressed: _getDate,
                  ),
                ],
              )
            )
          ],
        ),
      ),
    );
  }

flutter插件开发学习之旅(4)-------检测GPS状态,打开GPS和显示经纬度实战

完整的代码已经传到我的github上面,大家可以到https://github.com/1144075799/flutter_GPS下载源码观看,可以的话,给一个star。这个项目还会继续完善下去…