Flutter 插件 - 尝试在空对象引用上调用虚拟方法

Flutter plugin - Attempt to invoke virtual method on a null object reference

我正在学习如何创建 Flutter Plugins 所以我决定创建一个蓝牙插件,我知道那里有很多可用的但这里的目的是学习。

我遇到的错误如下

E/MethodChannel#flutterpluginbluetooth(22072): Failed to handle method call
E/MethodChannel#flutterpluginbluetooth(22072): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Context.registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)' on a null object reference

我不是 Java 开发人员,我确信这不是很好的方法,所以暂时忽略该方法。

这是我的onMethodCall

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } else if (call.method.equals("getMessage")) {
      BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      result.success("hello");


      System.out.println("DEBUG - Starting discovery");
      bluetoothAdapter.startDiscovery();
      final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
          System.out.println("DEBUG - inside onReceive");
          String action = intent.getAction();
          System.out.println("DEBUG - Action is: " + action);
          //Finding devices
          if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            System.out.println("Device Name: "  + device.getName());
          } else {
            System.out.println("DEBUG: Action did not match"  + BluetoothDevice.ACTION_FOUND);
          }
        }

      };
      IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
      System.out.println("DEBUG - About to registerReceiver");
      context.registerReceiver(mReceiver, filter);


    }
    else {
      result.notImplemented();
    }

  }

我的问题是为什么我在这个 context.registerReceiver(mReceiver, filter);

上收到错误

我也在阅读 android 文档,它在没有任何上下文的情况下调用 registerReceiver,如果我尝试这种方法,我也会收到一个错误,如下所示,它发生在编译期间.

error: cannot find symbol registerReceiver(mReceiver, filter);

这是onAttachedToEngine

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "flutterpluginbluetooth");
    channel.setMethodCallHandler(this);
  }

关于 Context

我只是导入它

import android.content.Context;

在 class 中我声明了一个 context 变量

private Context context;

非常感谢您的帮助。

您似乎没有初始化 context,您可以在 onAttachedToEngine 中使用 flutterPluginBinding 来做到这一点,例如;

context = flutterPluginBinding.getApplicationContext();