flutter插件开发学习之旅(3)-------检测蓝牙状态和打开蓝牙实战

检测蓝牙状态和打开蓝牙实战

前言

经过上二篇的学习,大家基本上应该明白flutter插件开发的基本流程。这篇博客就来一次实战吧,我曾经百度过,还没有关于蓝牙的插件。但是我们开发关于蓝牙的项目,就研究了flutter调用原生蓝牙api,在这个给大家分享一下。

准备工具

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

实战开始

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

 ///Flutter 调用原生 Start//

	//这里的参数名要和底层原生的申明的参数名一样
  static const MethodChannel methodChannel=
      MethodChannel('samples.flutter.io/bluetooth');

  Future<void> _openBlueTooth()async{		//打开蓝牙
    String message;
    message=await methodChannel.invokeMethod('openBuleTooth');
    setState(() {
      _message=message;
    });
  }

  Future<void> _getBlueTooth()async{     //检测蓝牙
    String message;
    message=await methodChannel.invokeMethod('getBuleTooth');
    setState(() {
      _message=message;
    });
  }

   Flutter 调用原生  End  

底层原生编写


public class MainActivity extends FlutterActivity {
	
  //申明方法名
  private static final String BLUETOOTH_CHANNEL="samples.flutter.io/bluetooth";

  private BluetoothManager bluetoothManager = null;	 //初始化
  private BluetoothAdapter bluetoothAdapter = null;	//蓝牙适配器

  @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("openBuleTooth")){	//判断flutter调用那个方法
                  if(supportBuleTooth()){						//检测真机是否支持蓝牙
                    openBuleTooth();							//打开蓝牙
                    result.success("蓝牙已经被开启");
                  }else{
                    result.error("设备不支持蓝牙",null,null);
                  }
                }
                else if(methodCall.method.equals("getBuleTooth")){
                  if(supportBuleTooth()){
                    if(disabled()){								//检测蓝牙的状态
                      result.success("蓝牙已经开启");
                    }else{
                      result.success("蓝牙未开启");
                    }
                  }
                }
              }
            }
    );
  }

  //是否支持蓝牙

  private boolean supportBuleTooth(){


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
      bluetoothManager=(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
      bluetoothAdapter=bluetoothManager.getAdapter();
    }
    if (bluetoothAdapter==null){    //不支持蓝牙
      return false;
    }
    return true;
  }

  //打开蓝牙
  private void openBuleTooth(){
    //判断蓝牙是否开启
      Intent enabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(enabler,1);
  }

  //判断蓝牙是否已经开启
  private boolean disabled(){
    if(bluetoothAdapter.isEnabled()){
      return true;
    }
    return false;
  }
}

下面就是进行简单的布局

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: new Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text('蓝牙状态:'),
                    Text(
                        _message,
                    )
                  ],
                ),
                Padding(
                  padding: EdgeInsets.all(10.0),
                  child:Column(
                    children: <Widget>[
                      RaisedButton(
                        color: Colors.blue,
                        textColor: Colors.white,
                        child: Text('打开蓝牙'),
                        onPressed: _openBlueTooth,
                      ),
                      RaisedButton(
                        color: Colors.blue,
                        textColor: Colors.white,
                        child: Text('检测蓝牙状态'),
                        onPressed: _getBlueTooth,
                      ),
                    ],
                  )
                )
              ],
            )
          ],
        ),
      ),
    );
  }

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

要在 Flutter 中调用 Android 原生代码,可以通过使用 Flutter 的平台通道(Platform Channel)来进行交互。下面是一个简单的示例,演示了如何调用 Android 原生代码: 1. 在 Flutter 项目的 `lib` 目录下创建一个新的 Dart 文件(例如 `native.dart`),用于定义与原生代码交互的接口。 ```dart import 'package:flutter/services.dart'; class NativeCode { static const platform = MethodChannel('com.example.app/native'); static Future<void> callNativeMethod() async { try { await platform.invokeMethod('nativeMethod'); } catch (e) { print(e); } } } ``` 2. 在 Android 项目的 `android/app/src/main/java/com/example/app` 目录下创建一个新的 Java 类(例如 `NativeChannel.java`),用于处理 Flutter 与原生代码之间的通信。 ```java package com.example.app; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; public class NativeChannel implements FlutterPlugin, MethodCallHandler { private MethodChannel channel; @Override public void onAttachedToEngine(FlutterPluginBinding flutterPluginBinding) { channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "com.example.app/native"); channel.setMethodCallHandler(this); } @Override public void onMethodCall(MethodCall call, Result result) { if (call.method.equals("nativeMethod")) { // 在这里编写你的原生代码逻辑 // ... result.success(null); // 返回结果给 Flutter } else { result.notImplemented(); } } @Override public void onDetachedFromEngine(FlutterPluginBinding binding) { channel.setMethodCallHandler(null); channel = null; } } ``` 3. 在 `MainActivity.java` 中注册 NativeChannel 插件: ```java import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; public class MainActivity extends FlutterActivity { @Override public void configureFlutterEngine(FlutterEngine flutterEngine) { super.configureFlutterEngine(flutterEngine); flutterEngine.getPlugins().add(new NativeChannel()); } } ``` 4. 在 Flutter 中调用原生方法,例如在一个按钮的点击事件中: ```dart ElevatedButton( onPressed: () { NativeCode.callNativeMethod(); }, child: Text('调用原生方法'), ) ``` 通过以上步骤,你就可以在 Flutter 中调用 Android 原生代码了。你可以根据需要扩展这个示例,添加更多的方法和参数来实现更复杂的交互。记得在调用原生方法时,遵循正确的线程调度和错误处理方式。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值