我正在学习如何创建Flutter插件,所以我决定创建一个蓝牙插件,我知道有很多可用的,但在这里学习的目的。
我面临的错误如下
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();
}
}
我的问题是为什么在这个上下文上出现错误。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);
}
关于上下文
我正在导入它
import android.content.Context;
在类内部,我声明了一个context
变量
private Context context;
我真的很感激你帮我。
您似乎没有初始化context
,您可以使用OnattachedToEngine
内部的FlutterPluginBinding
来初始化Context
,例如;
context = flutterPluginBinding.getApplicationContext();