flutter插件开发,监听原生广播返回数据

flutter自学交流群1102781545,欢迎提问
全部源码在这里获取https://github.com/mdddj/shangmi_scan_data_flutter

1

咳咳,先新建一个flutter 插件项目,因为我有java基础,所以用java语言创建
打开命令行

flutter create -i objc -a java --template=plugin 插件名字

image.png

看到底部出现All done!可以关掉了.

2

android studio 打开刚才创建的flutter 项目,它的结构类似这样的


image.png

先不要动代码,用安卓原生编辑器打开项目


image.png

 private EventChannel eventChannel;
 private Context applicationContext;

 /// 广播名 ACTION 
 private static final String ACTION_DATA_CODE_RECEIVED =
         "nlscan.action.SCANNER_RESULT";

// flutter app里面要监听数据流,先不管
 private static final String CHARGING_CHANNEL = "xindalu_scan/send";
image.png

onAttachedToEngine方法中添加下面的代码

   eventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), CHARGING_CHANNEL);
    eventChannel.setStreamHandler(new EventChannel.StreamHandler() {

      private BroadcastReceiver chargingStateChangeReceiver;

      @Override
      public void onListen(Object arguments, EventChannel.EventSink events) {
        chargingStateChangeReceiver = createChargingStateChangeReceiver(events);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_DATA_CODE_RECEIVED);
        applicationContext.registerReceiver(
                chargingStateChangeReceiver, filter);
      }

      @Override
      public void onCancel(Object arguments) {
        applicationContext.unregisterReceiver(chargingStateChangeReceiver);
        chargingStateChangeReceiver = null;
      }
    });


    applicationContext = flutterPluginBinding.getApplicationContext();

把上面的代码添加在这里


image.png

加完会报错,缺少一个方法,复制下面这段代码加到类里面


  private BroadcastReceiver createChargingStateChangeReceiver(final EventChannel.EventSink events) {
    return new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        String scanResult_1 = intent.getStringExtra("code1");
        String scanResult_2 = intent.getStringExtra("code2");
        int barcodeType = intent.getIntExtra("SCAN_BARCODE_TYPE", -1); // -1:unknown
        String scanStatus = intent.getStringExtra("SCAN_STATE");
        System.out.println(scanResult_1 + "  -  " + scanResult_2 + " - " + barcodeType + " --- " + scanStatus);
        Map<String,Object> resultMap = new HashMap<>();
        if ("ok".equals(scanStatus)) {
          //成功
          resultMap.put("code1",scanResult_1);
          resultMap.put("code2",scanResult_2);
          resultMap.put("SCAN_BARCODE_TYPE",barcodeType);
          resultMap.put("SCAN_STATE",scanStatus);

          // Map 转 json
          String json = JSONObject.toJSONString(resultMap);
          events.success(json);
        } else {
          //失败如超时等
          events.error("10000", "扫描超时", "请重新扫描");
        }
      }
    };
  }
image.png

小白第一次接触,大佬勿喷,有问题留言看到会回复

加个我看的文档把


image.png

推荐阅读更多精彩内容