当前位置: 首页 > 知识库问答 >
问题:

Flutter静态编程语言从广播接收机获取数据

陆野
2023-03-14

我正在尝试拥有自己的蓝牙kotlin实现,但遇到了一个问题。

我正在按照这里的kotlin教程启动一个用于扫描蓝牙设备的广播接收器。

问题是,当我试图从广播接收器将每个发现的设备添加到主活动范围内的可变列表中,以便将列表发送到颤振端时,我总是得到一个空值。

由于我是kotlin和android的新手,我无法真正理解我到底哪里出错了,以及我需要了解哪些概念才能做我需要做的事情。

Kotlin主要活动。千吨级


class MainActivity : FlutterActivity() {

    private val CHANNEL = "bluetooth.channel"
     var deviceList: MutableList<BluetoothDevice>?=null;

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {

        GeneratedPluginRegistrant.registerWith(flutterEngine);
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->

            when (call.method) {
                "getBlue" -> bluetoothWrapper(result)
                "discoverBlue" -> discoverDevices(deviceList,result)
            }
        }
    }

    private fun bluetoothWrapper(result: MethodChannel.Result) {
        val defaultAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
        checkAdapter(result, defaultAdapter);
        enableAdapter(defaultAdapter!!);
    }


    private fun checkAdapter(result: MethodChannel.Result, defaultAdapter: BluetoothAdapter?) {   // check if adapter exists
        if (defaultAdapter == null) {
            result.error("Bluetooth adapter doesn't exist on this device", null, null)
        } else {
            result.success("bluetooth adapter exists on device")
        }


    }

    // check if adapter is enabled if it exists, enable it if it isnt

    @SuppressLint("MissingPermission")
    private fun enableAdapter(bluetoothAdapter: BluetoothAdapter) {
        val requestEnableBt = 1;
        if (!bluetoothAdapter.isEnabled) {
            val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableIntent, requestEnableBt)
        }
    }

    // register broadcast receiver in order to discover available devices

    private fun discoverDevices(deviceList: MutableList<BluetoothDevice>?, result: MethodChannel.Result) {
        val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)

        registerReceiver(receiver, filter);

        result.success(deviceList)
    }
    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    deviceList?.add(device)

                    println("device found has selected parameters inside the broadcast receivver function $device")
                }
                "" -> println("broadcast receiver intent.action has no attribute")
                null -> println("broadcast receiver intent.action was null")
            }
        }
    }
}


颤振总管。飞奔

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatelessWidget {
  static const platform = const MethodChannel('bluetooth.channel');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Native'),
        centerTitle: true,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                color: Colors.blue[500],
                onPressed: () {
                  printMethod();
                },
                child: Text('connect to Devices'),
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                color: Colors.blue[500],
                onPressed: () {
                  discoverBlue();
                },
                child: Text('Discover devices'),
              )
            ],
          )
        ],
      ),
    );
  }

  void printMethod() async {
    String value;
    try {
      value = await platform.invokeMethod("getBlue");
    } catch (e) {
      print(e);
    }
    print('printing from dart: $value');
  }

  void discoverBlue() async {
    Future<List> list;
    list = platform.invokeListMethod("discoverBlue", list);
    list.then((val) {
      print("got values from kotlin $val");
    });
  }
}

共有1个答案

田修为
2023-03-14

我看到你还没有触发启动发现过程。你需要做

        val myAdapter = BluetoothAdapter.getDefaultAdapter();
        myAdapter.startDiscovery();

另外,因为它在kotlin中是异步任务。返回结果

BluetoothAdapter.ACTION_DISCOVERY_FINISHED

所以你的MainActivity.kt会是

package com.example.testapp

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant


class MainActivity : FlutterActivity() {

    private val CHANNEL = "bluetooth.channel"
    var deviceList: MutableList<BluetoothDevice>? = null;

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {

        GeneratedPluginRegistrant.registerWith(flutterEngine);
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->

            when (call.method) {
                "getBlue" -> bluetoothWrapper(result)
                "discoverBlue" -> discoverDevices(deviceList, result)
                "allPaired" -> getConnectedDevices(result)
            }
        }
    }

    private fun getConnectedDevices(result: MethodChannel.Result) {
        val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        val pairedDevices = mBluetoothAdapter.bondedDevices

        val s: MutableList<String> = ArrayList()
        for (bt in pairedDevices) s.add(bt.name)
        result.success(s);
    }

    private fun bluetoothWrapper(result: MethodChannel.Result) {
        val defaultAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
        checkAdapter(result, defaultAdapter);
        enableAdapter(defaultAdapter!!);
    }


    private fun checkAdapter(result: MethodChannel.Result, defaultAdapter: BluetoothAdapter?) {   // check if adapter exists
        if (defaultAdapter == null) {
            result.error("Bluetooth adapter doesn't exist on this device", null, null)
        } else {
            result.success("bluetooth adapter exists on device")
        }


    }

    // check if adapter is enabled if it exists, enable it if it isnt

    @SuppressLint("MissingPermission")
    private fun enableAdapter(bluetoothAdapter: BluetoothAdapter) {
        val requestEnableBt = 1;
        if (!bluetoothAdapter.isEnabled) {
            val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableIntent, requestEnableBt)
        }
    }

    // register broadcast receiver in order to discover available devices

    private fun discoverDevices(deviceList: MutableList<BluetoothDevice>?, result: MethodChannel.Result) {

        val myAdapter = BluetoothAdapter.getDefaultAdapter();
        myAdapter.startDiscovery();

        val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
        val receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                when (intent.action) {
                    BluetoothDevice.ACTION_FOUND -> {
                        val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                        deviceList?.add(device)
                        println("device found has selected parameters inside the broadcast receivver function $device")
                    }
                    BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                        result.success(deviceList)
                    }
                    "" -> println("broadcast receiver intent.action has no attribute")
                    null -> println("broadcast receiver intent.action was null")
                }
            }
        }
        registerReceiver(receiver, filter)
    }


}

和main。dart将是

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatelessWidget {
  static const platform = const MethodChannel('bluetooth.channel');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Native'),
        centerTitle: true,
      ),
      body: Container(
        width: double.infinity,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              color: Colors.blue[500],
              onPressed: () {
                printMethod();
              },
              child: Text('connect to Devices'),
            ),
            RaisedButton(
              color: Colors.blue[500],
              onPressed: () {
                discoverBlue();
              },
              child: Text('Discover devices'),
            ),
            RaisedButton(
              color: Colors.blue[500],
              onPressed: () {
                getAllPaired();
              },
              child: Text('All paired devices'),
            )
          ],
        ),
      ),
    );
  }

  void printMethod() async {
    String value;
    try {
      value = await platform.invokeMethod("getBlue");
    } catch (e) {
      print(e);
    }
    print('printing from dart: $value');
  }

  void discoverBlue() async {
    Future<List> list;
    list = platform.invokeListMethod("discoverBlue", list);
    list.then((val) {
      print("got values from kotlin $val");
    });
  }

  void getAllPaired() async {
    var value = await platform.invokeListMethod("allPaired");
    print(value);
  }
}

 类似资料:
  • 我们都知道,我们注册广播接收机有两种类型 动态注册 但我的疑问是什么时候我们需要使用,什么时候我们需要使用?

  • 清单中是否需要receiver/intent-filter块,如果需要,如何在第一行中命名侦听器? 在onReceive()中无法收到传入消息副本的可能原因是什么?我应该做些什么来更正它? 我是否需要发送消息并在onReceive()中“捕获它”以便可靠地获得设备的电话号码,或者我是否可以从用户那里请求读取SMS的权限,然后只需读取第一条消息即可获得传入的电话号码? 请注意,我已经通读了所有类似的

  • 它与扩展函数有什么关系?为什么带有的是函数,而不是关键字? 这个主题似乎没有明确的留档,只有关于扩展的知识假设。

  • 我试图用OkHttp和Cucumber在静态编程语言中设置一个Spring启动项目,并且在运行Cucumber任务时遇到以下错误。如何修复? 还有build gradle kts片段 我看到了这个错误https://github.com/square/okio/issues/647看起来可能是它,并修复了这个build.gradle,我如何将其翻译为kotlinbuild.gradle.kts?

  • 我是android新手。我的项目有一个活动和一个服务。我的服务有一个广播接收器,而活动有一个广播发送器,它在PeriodSender方法中。动态地,当我注册接收者时,在服务开始时它不会调用,但是如果我在几分钟后发送了一些东西,它就会调用。但是我想在清单中注册它,我已经在清单中包含了接收方的详细信息,但是接收方没有调用。我的接收方类名是MyReceiver21,意图操作是My_ACTION1。实际上

  • 是否有可能在Kotlin 属性初始化之前从其获取< code>::class.java? 从逻辑上讲,它应该可以工作——我试图获取一个类而不是一个值,但实际上它在未初始化的属性访问异常时失败。 请注意,我试图获取类的属性位于泛型类中,其类型是泛型参数之一: 我需要这个类来创建的实例 当然,我不能做到: 对此有什么解决办法吗?