简体   繁体   English

如何读写Android NFC标签?

[英]How to read and write Android NFC tags?

I followed some tutorial using the adam rocker source code for my NFCTest.我按照一些教程使用我的 NFCTest 的 Adam Rocker 源代码。 I want to be able to read and write NFC tags and also launch an application.我希望能够读写 NFC 标签并启动应用程序。

The NDEF Tools for Android utility project helps doing the following Android实用程序项目的NDEF 工具有助于执行以下操作

  1. Detect , then 检测,然后
  2. Read or write , or ,或
  3. Beam (push) NFC content 光束(推)NFC 内容

The project also includes data bindings for all standardized NDEF record types, which really simplifies things compared to working with the (byte-array-based) NDEF classes included in the Android SDK.该项目还包括所有标准化 NDEF 记录类型的数据绑定,与使用 Android SDK 中包含的(基于字节数组的)NDEF 类相比,这确实简化了事情。

Also see the NFC Eclipse plugin for a graphical NDEF editor - comes with an utility app which reads and writes to tags and beams, also has NFC reader integration.另请参阅图形 NDEF 编辑器的NFC Eclipse 插件- 附带一个实用程序应用程序,可读取和写入标签和光束,还具有 NFC 阅读器集成。

By the way, you are looking for the Android Application Record for launching the app.顺便说一下,您正在寻找用于启动应用程序的 Android 应用程序记录。 The launching 'feature' does not require any real implementation;启动“功能”不需要任何实际实现; it is built into Android >= 4.0, so putting that record on a tag is enough.它内置在 Android >= 4.0 中,因此将该记录放在标签上就足够了。

First of all you have to get permission in AndroidManifest.xml file for NFC.首先,您必须在 AndroidManifest.xml 文件中获得 NFC 的许可。 The permissions are:权限是:

<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" />

The Activity which will perform NFC Read/write operation, add this intent filter in that activity in AndroidManifest.xml file:将执行 NFC 读/写操作的活动,在 AndroidManifest.xml 文件中的该活动中添加此意图过滤器:

          <intent-filter>
            <action android:name="android.nfc.action.TAG_DISCOVERED" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

In your activity onCreate() method you have to initialize the NFC adapter and define Pending Intent :在您的活动 onCreate() 方法中,您必须初始化 NFC 适配器并定义 Pending Intent :

NfcAdapter mAdapter;
PendingIntent mPendingIntent;
mAdapter = NfcAdapter.getDefaultAdapter(this);   
if (mAdapter == null) {
    //nfc not support your device.
    return;
}
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
        getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

In onResume() Call back enable the Foreground Dispatch to detect NFC intent.在 onResume() 回调中启用前台调度以检测 NFC 意图。

mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);

In onPause() callback you must have to disable the forground dispatch:在 onPause() 回调中,您必须禁用前台调度:

    if (mAdapter != null) {
        mAdapter.disableForegroundDispatch(this);
    }

In onNewIntent() call back method you will get the new Nfc Intent.在 onNewIntent() 回调方法中,您将获得新的 Nfc Intent。 After getting The Intent , you have to parse the intent to detect the card:获得 The Intent 后,您必须解析 Intent 以检测卡片:

@Override
protected void onNewIntent(Intent intent){    
    getTagInfo(intent)
}

private void getTagInfo(Intent intent) {
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}

Now You have the Tag.现在你有了标签。 Then you can check the Tag Tech list to detect that Tag.然后您可以检查标签技术列表以检测该标签。 The tag detection technique is here in My Another Answer Full complete project is here in My github profile标签检测技术在我的另一个答案中完整的项目在我的 github 个人资料中

Put these in your manifest :把这些放在你的清单中:

<uses-permission android:name="android.permission.NFC" />
    <uses-permission android:name="android.permission.INTERNET" />

Then to read NFC put this part in your activity:然后阅读NFC把这部分放在你的活动中:

<intent-filter>
                <action android:name="android.nfc.action.TAG_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

at the end add go forward like my Activity :最后添加像我的 Activity 一样前进:

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.balysv.materialripple.MaterialRippleLayout;
import com.blogspot.android_er.androidnfctagdiscovered.R;
import com.pixelcan.inkpageindicator.InkPageIndicator;

import hpbyp.ir.app.hojre.fragment.slider.SliderPagerAdapter;
import hpbyp.ir.app.hojre.utiles.G;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

/**
 * An {@link Activity} which handles a broadcast of a new tag that the device just discovered.
 */
public class ActivityLoadDataFromNFC extends AppCompatActivity {
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load_data_from_nfc);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null) {
            //nfc not support your device.
            return;
        }
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    }

    NfcAdapter mAdapter;
    PendingIntent mPendingIntent;

    @Override
    protected void onResume() {
        super.onResume();
        mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAdapter != null) {
            mAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        GetDataFromTag(tag, intent);

    }

    private void GetDataFromTag(Tag tag, Intent intent) {
        Ndef ndef = Ndef.get(tag);
        try {
            ndef.connect();
//            txtType.setText(ndef.getType().toString());
//            txtSize.setText(String.valueOf(ndef.getMaxSize()));
//            txtWrite.setText(ndef.isWritable() ? "True" : "False");
            Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

            if (messages != null) {
                NdefMessage[] ndefMessages = new NdefMessage[messages.length];
                for (int i = 0; i < messages.length; i++) {
                    ndefMessages[i] = (NdefMessage) messages[i];
                }
                NdefRecord record = ndefMessages[0].getRecords()[0];

                byte[] payload = record.getPayload();
                String text = new String(payload);
                Log.e("tag", "vahid" + text);
                ndef.close();

            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Cannot Read From Tag.", Toast.LENGTH_LONG).show();
        }
    }

}

您可以在此处找到一个带有示例的简单 NFC 库: https : //github.com/mateuyabar/pillowNFC

I think the code you found refers to the pre 2.3.3 era.我认为您找到的代码是指 2.3.3 之前的时代。 At this point it was not able to write a tag, but with Android 2.3.3 this is possible.此时它无法写入标签,但在 Android 2.3.3 中这是可能的。 There is no need trying to hack the system and write tags like this.没有必要试图破解系统并编写这样的标签。

Have a look at the NFC Demo Project: http://developer.android.com/resources/samples/NFCDemo/index.html看看NFC演示项目: http : //developer.android.com/resources/samples/NFCDemo/index.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM