启动 Flutter App/通过 NFC NDEF AAR 记录将其带到前台,无法在同一读取中访问附加信息

问题描述 投票:0回答:1

我正在尝试启动我的应用程序并同时从 NFC 芯片读取一些数据,将数据传递给 Flutter,以便我可以在应用程序中处理它。

这是我所做的:

修改后的MainActivity.kt

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.test.test/nfc"
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "onNFCDiscovered") {
                result.success("Method handled successfully")
            } else {
                result.notImplemented()
            }
        }
    }
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        handleIntent(intent)
    }

    private fun handleIntent(intent: Intent) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action) {
            val rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
            if (rawMessages != null) {
                val messages = rawMessages.map { it as NdefMessage }
                val record = messages.first().records.first()
                val payload = String(record.payload)
                MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, CHANNEL).invokeMethod("onNFCDiscovered", payload)
        }
    }
}

向 AndroidManifest.xml 添加了权限和此意图过滤器:

<intent-filter>
     <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
     <category android:name="android.intent.category.DEFAULT"/>
     <data android:mimeType="application/com.test.test"/>
</intent-filter>

在 flutter 控制器中设置方法通道监听器:

class LoggingController extends GetxController {
  static const platform = MethodChannel('com.test.test/nfc');

  LoggingController() {
    platform.setMethodCallHandler((call) async {
      if (call.method == "onNFCDiscovered") {
        log("NFC Tag Data: ${call.arguments}");
      }
    });
  }
}

到目前为止,应用程序启动了,但我尝试读取存储在芯片上的附加数据并将其同时传递给 Flutter 的尝试都没有成功。

android flutter kotlin dart nfc
1个回答
0
投票

问题我相信onNewIntent仅被调用

活动重新启动时

因此,如果您使用清单意图过滤器启动应用程序,则其中包含 Ndef 消息的意图将被传递到

onCreate
onNewIntent
永远不会被调用,因为还没有要重新启动的 Activity。

正如您所说,意图处理是一个单独的方法,然后在

onCreate
方法中添加

// get the Intent the App was started with
val mIntent = getIntent()
handleIntent(mIntent)

这与我在应用程序中所做的类似,一次性启动并读取标签。

© www.soinside.com 2019 - 2024. All rights reserved.