【问题标题】:Is there a way to create an ACTION_NDEF_DISCOVERED intent from code有没有办法从代码创建 ACTION_NDEF_DISCOVERED 意图
【发布时间】:2014-11-03 11:06:05
【问题描述】:

对于我正在编写的应用程序,我想知道是否可以从代码创建 ACTION_NDEF_DISCOVERED 意图。通常,此意图是由系统在读取 ndef 格式的标签时创建的。它包含一个类型为 Tag 的 parcableextra。

意图的创建可能很容易,但您是否也可以从代码中创建一个标签,或者我认为该类不支持该标签。

目标是将带有 ndef 记录的虚拟标签广播到系统,然后可以由调用 ACTION_NDEF_DISCOVERED 意图的应用程序处理。

【问题讨论】:

    标签: android android-intent tags nfc ndef


    【解决方案1】:

    您可以使用反射获得一个模拟标记对象实例。像这样的东西应该可以工作:

    NdefMessage ndefMsg = ...;
    
    Class tagClass = Tag.class;
    Method createMockTagMethod = tagClass.getMethod("createMockTag", byte[].class, int[].class, Bundle[].class);
    
    final int TECH_NFC_A = 1;
    final int TECH_NDEF = 6;
    
    final String EXTRA_NDEF_MSG = "ndefmsg";
    final String EXTRA_NDEF_MAXLENGTH = "ndefmaxlength";
    final String EXTRA_NDEF_CARDSTATE = "ndefcardstate";
    final String EXTRA_NDEF_TYPE = "ndeftype";
    
    Bundle ndefBundle = new Bundle();
    ndefBundle.putInt(EXTRA_NDEF_MSG, 48); // result for getMaxSize()
    ndefBundle.putInt(EXTRA_NDEF_CARDSTATE, 1); // 1: read-only, 2: read/write
    ndefBundle.putInt(EXTRA_NDEF_TYPE, 2); // 1: T1T, 2: T2T, 3: T3T, 4: T4T, 101: MF Classic, 102: ICODE
    ndefBundle.putParcelable(EXTRA_NDEF_MSG, ndefMsg);
    
    Tag mockTag = (Tag)createMockTagMethod.invoke(null,
            new byte[] { (byte)0x12, (byte)0x34, (byte)0x56, (byte)0x78 },
            new int[] { TECH_NFC_A, TECH_NDEF },
            new Bundle[] { null, ndefBundle });
    

    这样做的问题是您将无法连接到此标签。因此,Ndef 对象的所有方法(您可以从该模拟 Tag 实例中获取)需要使用真实标签或向 NFC 服务注册的真实标签进行 IO 操作的所有方法都将失败。具体来说,只有

    • getCachedNdefMessage(),
    • getMaxSize(),
    • getType(),
    • isWritable(),和
    • getTag()

    会起作用的。

    因此,如果您不将Tag 对象作为NDEF_DISCOVERED 意图的一部分传递,而是仅使用EXTRA_NDEF_MESSAGES 意图额外,那么几乎可以使用相同的功能。

    【讨论】:

      猜你喜欢
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      相关资源
      最近更新 更多