【问题标题】:How to read URL in NFC in android如何在android中读取NFC中的URL
【发布时间】:2015-05-26 04:34:35
【问题描述】:

我使用this 代码将NFC 阅读集成到我的android 应用程序中。将纯文本写入NFC 标签并使用应用程序读取它是完美的工作。现在我的要求是从NFC标签读取URL。当从NFC标签读取值时,它会自动打开浏览器并加载URL。那么实现读取内容并打开我的应用程序需要进行哪些更改?

【问题讨论】:

    标签: android nfc reader


    【解决方案1】:

    添加到您的清单

       <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    
                <data
                    android:host="your host name"
                    android:scheme="http" />
    
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
    

    在您要打开的活动中

    【讨论】:

    • 你能解释一下如何添加主机名吗?
    【解决方案2】:

    这里我假设返回的结果只有url,没有其他数据,所以只需将onPostExecute修改为:

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            String url = result;
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }
    }
    

    如果还包括其他数据而不是解析结果以仅获取 URL。

    【讨论】:

      【解决方案3】:

      如果您想在靠近 NFC 标签时启动应用程序,您可以使用过滤器,但请注意,如果您的应用程序正在运行,它将不会收到有关标签的通知。您必须在您的应用中注册它:

      protected void onCreate(Bundle savedInstanceState) {
          ...
          Intent nfcIntent = new Intent(this, getClass());
          nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      
          nfcPendingIntent =
                  PendingIntent.getActivity(this, 0, nfcIntent, 0);
      
          IntentFilter tagIntentFilter =
                  new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
          try {
              tagIntentFilter.addDataType("text/plain");
              intentFiltersArray = new IntentFilter[]{tagIntentFilter};
          }
          catch (Throwable t) {
              t.printStackTrace();
          }
      }
      

      记得在 onResume 中启用它:

      nfcAdpt.enableForegroundDispatch(
                  this,
                  nfcPendingIntent,
                  intentFiltersArray,
                  null);
          handleIntent(getIntent());
      

      并在 onPause 中取消注册:

      nfcAdpt.disableForegroundDispatch(this);

      ..请注意,数据可以存储在您的 NFC 标签中的 SmartPoster 结构中。在这种情况下,您必须以另一种方式阅读它。 在我的博客中你可以找到一篇关于阅读的帖子SmartPoster and more

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多