How to read and write Android NFC tags?

最后都变了- 提交于 2019-12-17 17:46:11

问题


I followed some tutorial using the adam rocker source code for my NFCTest. I want to be able to read and write NFC tags and also launch an application.


回答1:


The NDEF Tools for Android utility project helps doing the following

  1. Detect, then
  2. Read or write, or
  3. Beam (push) NFC content

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.

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.

By the way, you are looking for the Android Application Record for launching the app. 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.




回答2:


First of all you have to get permission in AndroidManifest.xml file for 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:

          <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 :

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.

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

In onPause() callback you must have to disable the forground dispatch:

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

In onNewIntent() call back method you will get the new Nfc Intent. After getting The Intent , you have to parse the intent to detect the card:

@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




回答3:


first of all put these in your manifest :

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

and then put this in your activity which you want to read 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 :

/* * Copyright (C) 2010 The Android Open Source Project * Copyright (C) 2011 Adam Nybäck * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */

package ***.***.***.***;

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();
        }
    }

}



回答4:


I think the code you found refers to the pre 2.3.3 era. At this point it was not able to write a tag, but with Android 2.3.3 this is possible. 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




回答5:


You can find a simple NFC library with an example here: https://github.com/mateuyabar/pillowNFC



来源:https://stackoverflow.com/questions/5546932/how-to-read-and-write-android-nfc-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!