zoukankan      html  css  js  c++  java
  • NFC读写实例

    package com.sy.nfc.test;
    
    import java.io.IOException;
    
    import android.nfc.NdefMessage;
    import android.nfc.NdefRecord;
    import android.nfc.NfcAdapter;
    import android.nfc.Tag;
    import android.nfc.tech.MifareClassic;
    import android.nfc.tech.Ndef;
    import android.nfc.tech.NdefFormatable;
    import android.nfc.tech.NfcA;
    import android.os.Bundle;
    import android.os.Parcelable;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.PendingIntent;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    /**
     * 
     * @author shenyang
     * @see
     * @des
     * 
     *      Nfc 标签的扫描
     * 
     * 
     */
    @SuppressLint("NewApi")
    public class ReadTag extends Activity {
        private NfcAdapter nfcAdapter;
        private TextView resultText;
        private PendingIntent pendingIntent;
        private IntentFilter[] mFilters;
        private String[][] mTechLists;
        private Button mJumpTagBtn;
        private boolean isFirst = true;
    
        @SuppressLint("NewApi")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // 获取nfc适配器,判断设备是否支持NFC功能
            nfcAdapter = NfcAdapter.getDefaultAdapter(this);
            if (nfcAdapter == null) {
                Toast.makeText(this, getResources().getString(R.string.no_nfc),
                        Toast.LENGTH_SHORT).show();
                finish();
                return;
            } else if (!nfcAdapter.isEnabled()) {
                Toast.makeText(this, getResources().getString(R.string.open_nfc),
                        Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
            setContentView(R.layout.read_tag);
            // 显示结果Text
            resultText = (TextView) findViewById(R.id.resultText);
            // 写入标签按钮
            mJumpTagBtn = (Button) findViewById(R.id.jump);
            mJumpTagBtn.setOnClickListener(new WriteBtnOnClick());
    
            pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                    getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
            ndef.addCategory("*/*");
            mFilters = new IntentFilter[] { ndef };// 过滤器
            mTechLists = new String[][] {
                    new String[] { MifareClassic.class.getName() },
                    new String[] { NfcA.class.getName() } };// 允许扫描的标签类型
    
        }
    
        @SuppressLint("NewApi")
        @Override
        protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
                    mTechLists);
            if (isFirst) {
                if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
                    String result = processIntent(getIntent());
                    resultText.setText(result);
                }
                isFirst = false;
            }
    
        }
    
        @Override
        protected void onNewIntent(Intent intent) {
            // TODO Auto-generated method stub
            super.onNewIntent(intent);
            if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
                String result = processIntent(intent);
                resultText.setText(result);
            }
        }
    
        /**
         * 获取tab标签中的内容
         * 
         * @param intent
         * @return
         */
        @SuppressLint("NewApi")
        private String processIntent(Intent intent) {
            Parcelable[] rawmsgs = intent
                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage msg = (NdefMessage) rawmsgs[0];
            NdefRecord[] records = msg.getRecords();
            String resultStr = new String(records[0].getPayload());
            return resultStr;
        }
    
        /**
         * 按钮点击事件
         * 
         * @author shenyang
         * 
         */
        class WriteBtnOnClick implements OnClickListener {
    
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                switch (v.getId()) {
                case R.id.jump:
                    Intent intent = new Intent(ReadTag.this, WriteTag.class);
                    startActivity(intent);
                default:
                    break;
                }
            }
    
        }
    
    }
    读标签内容代码展开
    package com.sy.nfc.test;
    
    import java.io.IOException;
    
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.PendingIntent;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.nfc.NdefMessage;
    import android.nfc.NdefRecord;
    import android.nfc.NfcAdapter;
    import android.nfc.Tag;
    import android.nfc.tech.MifareClassic;
    import android.nfc.tech.Ndef;
    import android.nfc.tech.NdefFormatable;
    import android.nfc.tech.NfcA;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    /**
     * 写入标签
     * 
     * @warn:弹出dialog 允许写入
     * @author shenyang
     * 
     */
    @SuppressLint("NewApi")
    public class WriteTag extends Activity {
    
        private IntentFilter[] mWriteTagFilters;
        private NfcAdapter nfcAdapter;
        PendingIntent pendingIntent;
        String[][] mTechLists;
        Button writeBtn;
        boolean isWrite = false;
        EditText mContentEditText;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.write_tag);
            writeBtn = (Button) findViewById(R.id.writeBtn);
            writeBtn.setOnClickListener(new WriteOnClick());
            mContentEditText = (EditText) findViewById(R.id.content_edit);
            // 获取nfc适配器,判断设备是否支持NFC功能
            nfcAdapter = NfcAdapter.getDefaultAdapter(this);
            if (nfcAdapter == null) {
                Toast.makeText(this, getResources().getString(R.string.no_nfc),
                        Toast.LENGTH_SHORT).show();
                finish();
                return;
            } else if (!nfcAdapter.isEnabled()) {
                Toast.makeText(this, getResources().getString(R.string.open_nfc),
                        Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
            pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                    getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            // 写入标签权限
            IntentFilter writeFilter = new IntentFilter(
                    NfcAdapter.ACTION_TECH_DISCOVERED);
            mWriteTagFilters = new IntentFilter[] { writeFilter };
            mTechLists = new String[][] {
                    new String[] { MifareClassic.class.getName() },
                    new String[] { NfcA.class.getName() } };// 允许扫描的标签类型
    
        }
    
        /**
         * 写入标签按钮点击事件监听
         * 
         * @author shenyang
         * 
         */
        class WriteOnClick implements OnClickListener {
    
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                isWrite = true;
                AlertDialog.Builder builder = new AlertDialog.Builder(WriteTag.this)
                        .setTitle("请将标签靠近!");
                builder.setNegativeButton("确定",
                        new DialogInterface.OnClickListener() {
    
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                dialog.dismiss();
                                mContentEditText.setText("");
                                isWrite = false;
                                WriteTag.this.finish();
                            }
                        });
                builder.setPositiveButton("取消",
                        new DialogInterface.OnClickListener() {
    
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                dialog.dismiss();
                                isWrite = false;
                            }
                        });
                builder.create();
                builder.show();
            }
        }
    
        @Override
        protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            nfcAdapter.enableForegroundDispatch(this, pendingIntent,
                    mWriteTagFilters, mTechLists);
        }
    
        // 写入模式时,才执行写入操作
        @Override
        protected void onNewIntent(Intent intent) {
            // TODO Auto-generated method stub
            super.onNewIntent(intent);
            if (isWrite == true
                    && NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                NdefMessage ndefMessage = getNoteAsNdef();
                if (ndefMessage != null) {
                    writeTag(getNoteAsNdef(), tag);
                } else {
                    showToast("请输入您要写入标签的内容");
                }
            }
        }
    
        // 根据文本生成一个NdefRecord
        private NdefMessage getNoteAsNdef() {
            String text = mContentEditText.getText().toString();
            if (text.equals("")) {
                return null;
            } else {
                byte[] textBytes = text.getBytes();
                // image/jpeg text/plain
                NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                        "image/jpeg".getBytes(), new byte[] {}, textBytes);
                return new NdefMessage(new NdefRecord[] { textRecord });
            }
    
        }
    
        // 写入tag
        boolean writeTag(NdefMessage message, Tag tag) {
    
            int size = message.toByteArray().length;
    
            try {
                Ndef ndef = Ndef.get(tag);
                if (ndef != null) {
                    ndef.connect();
    
                    if (!ndef.isWritable()) {
                        showToast("tag不允许写入");
                        return false;
                    }
                    if (ndef.getMaxSize() < size) {
                        showToast("文件大小超出容量");
                        return false;
                    }
    
                    ndef.writeNdefMessage(message);
                    showToast("写入数据成功.");
                    return true;
                } else {
                    NdefFormatable format = NdefFormatable.get(tag);
                    if (format != null) {
                        try {
                            format.connect();
                            format.format(message);
                            showToast("格式化tag并且写入message");
                            return true;
                        } catch (IOException e) {
                            showToast("格式化tag失败.");
                            return false;
                        }
                    } else {
                        showToast("Tag不支持NDEF");
                        return false;
                    }
                }
            } catch (Exception e) {
                showToast("写入数据失败");
            }
    
            return false;
        }
    
        private void showToast(String text) {
            Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
        }
    }
    写入标签代码展开
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.sy.nfc.test"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />
    
        <uses-permission android:name="android.permission.NFC" />
    
        <uses-feature
            android:name="android.hardware.nfc"
            android:required="true" />
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.sy.nfc.test.ReadTag"
                android:label="@string/app_name"
                android:launchMode="singleTop" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
                <intent-filter>
                    <action android:name="android.nfc.action.TECH_DISCOVERED" />
                </intent-filter>
    
                <meta-data
                    android:name="android.nfc.action.TECH_DISCOVERED"
                    android:resource="@xml/nfc_tech_filter" />
            </activity>
            <activity android:name="com.sy.nfc.test.WriteTag" >
                <intent-filter>
                    <action android:name="android.nfc.action.TAG_DISCOVERED" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
    配置文件展开

    已经非常详细了。源码下载:

    http://download.csdn.net/detail/sy_hx/6307597

    可以直接运行。主要就是NFC的读写实例。有需要的下载看看

    点我下载

  • 相关阅读:
    spring 配置多个properties
    redis 一些使用过的命令
    ftpclient 遇到的一些问题
    tomcat+nginx 横向扩展
    easyui 刷新页面
    tomcat 发布本地文件
    java httpclient 跳过证书验证
    https增加临时证书,tomcat配置
    echarts getAttribute”的值: 对象为 null 或未定义 错误解决方法,
    数据的导入导出
  • 原文地址:https://www.cnblogs.com/sy171822716/p/3334925.html
Copyright © 2011-2022 走看看