溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

android中NFC讀寫功能的實(shí)現(xiàn)方法是怎樣的

發(fā)布時(shí)間:2021-09-24 16:20:17 來源:億速云 閱讀:183 作者:柒染 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)android中NFC讀寫功能的實(shí)現(xiàn)方法是怎樣的,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

首先檢查一下設(shè)備是否支持NFC功能

private void checkNFCFunction() {
        // TODO Auto-generated method stub
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        // check the NFC adapter first
        if (mNfcAdapter == null) {
            // mTextView.setText("NFC apdater is not available");
            Dialog dialog = null;
            AlertDialog.Builder customBuilder = new AlertDialog.Builder(
                    this);
            customBuilder
                    .setTitle("很遺憾")
                    .setMessage("沒發(fā)現(xiàn)NFC設(shè)備,請確認(rèn)您的設(shè)備支持NFC功能!")
                    .setIcon(R.drawable.ic_banner)
                    .setPositiveButton("是",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();
                                    finish();
                                }
                            });
            dialog = customBuilder.create();
            dialog.setCancelable(false);// back
            dialog.setCanceledOnTouchOutside(false);
            SetDialogWidth(dialog).show();
            return;
        } else {
            if (!mNfcAdapter.isEnabled()) {
                Dialog dialog = null;
                AlertDialog.Builder customBuilder = new AlertDialog.Builder(
                        this);
                customBuilder
                        .setTitle("提示")
                        .setMessage("請確認(rèn)NFC功能是否開啟!")
                        .setIcon(R.drawable.ic_banner)
                        .setPositiveButton("現(xiàn)在去開啟......",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.dismiss();
                                        Intent setnfc = new Intent(
                                                Settings.ACTION_NFC_SETTINGS);
                                        startActivity(setnfc);
                                    }
                                });
                dialog = customBuilder.create();
                dialog.setCancelable(false);// back
                dialog.setCanceledOnTouchOutside(false);
                SetDialogWidth(dialog).show();
                return;
            }
        }
    }

讀取NFC信息

package com.xxzhy.shujucaiji.fengxiang;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
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.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xxzhy.shujucaiji.R;
import com.xxzhy.shujucaiji.utils.ByteArrayChange;
import com.xxzhy.shujucaiji.utils.ToStringHex;
import com.xxzhy.shujucaiji.utils.ToastUtil;
import com.xxzhy.shujucaiji.utils.WebServiceClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * Created by apple on 2017/10/30.
 */

public class FengxiangThreeActivity extends AppCompatActivity {

    @BindView(R.id.tv_bianma)
    TextView tvBianma;
    @BindView(R.id.ll_input)
    LinearLayout llInput;
    @BindView(R.id.noteText)
    TextView noteText;
    @BindView(R.id.writeBtn)
    Button writeBtn;
    String[][] mTechLists;
    private Boolean ifWrite;
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    byte[] code = MifareClassic.KEY_DEFAULT;//讀寫標(biāo)簽中每個(gè)塊的密碼
    private byte[] b0;
    int block[] = {4, 5, 6, 8, 9, 10, 12, 13, 14, 16, 17, 18, 20, 21, 22, 24,
            25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42, 44, 45, 46,
            48, 49, 50, 52, 53, 54, 56, 57, 58, 60, 61, 62};
    private String samCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fengxiang_three);
        ButterKnife.bind(this);
        writeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ifWrite = true;
            }
        });
        samCode = getIntent().getStringExtra("samCode");
        tvBianma.setText(samCode);
        checkNFCFunction(); // NFC Check

        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        // Setup an intent filter for all MIME based dispatches
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[]{ndef,};

        // 根據(jù)標(biāo)簽類型設(shè)置
        mTechLists = new String[][]{new String[]{NfcA.class.getName()}};
    }

    private void checkNFCFunction() {
        // TODO Auto-generated method stub
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        // check the NFC adapter first
        if (mNfcAdapter == null) {
            // mTextView.setText("NFC apdater is not available");
            Dialog dialog = null;
            AlertDialog.Builder customBuilder = new AlertDialog.Builder(
                    this);
            customBuilder
                    .setTitle("很遺憾")
                    .setMessage("沒發(fā)現(xiàn)NFC設(shè)備,請確認(rèn)您的設(shè)備支持NFC功能!")
                    .setIcon(R.drawable.ic_banner)
                    .setPositiveButton("是",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();
                                    finish();
                                }
                            });
            dialog = customBuilder.create();
            dialog.setCancelable(false);// back
            dialog.setCanceledOnTouchOutside(false);
            SetDialogWidth(dialog).show();
            return;
        } else {
            if (!mNfcAdapter.isEnabled()) {
                Dialog dialog = null;
                AlertDialog.Builder customBuilder = new AlertDialog.Builder(
                        this);
                customBuilder
                        .setTitle("提示")
                        .setMessage("請確認(rèn)NFC功能是否開啟!")
                        .setIcon(R.drawable.ic_banner)
                        .setPositiveButton("現(xiàn)在去開啟......",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.dismiss();
                                        Intent setnfc = new Intent(
                                                Settings.ACTION_NFC_SETTINGS);
                                        startActivity(setnfc);
                                    }
                                });
                dialog = customBuilder.create();
                dialog.setCancelable(false);// back
                dialog.setCanceledOnTouchOutside(false);
                SetDialogWidth(dialog).show();
                return;
            }
        }
    }

    private Dialog SetDialogWidth(Dialog dialog) {
        // TODO 自動(dòng)生成的方法存根
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        if (screenWidth > screenHeight) {
            params.width = (int) (((float) screenHeight) * 0.875);

        } else {
            params.width = (int) (((float) screenWidth) * 0.875);
        }
        dialog.getWindow().setAttributes(params);

        return dialog;
    }


    @Override
    protected void onNewIntent(Intent intent) {
        // TODO 自動(dòng)生成的方法存根
        super.onNewIntent(intent);
//        tv1.setText("發(fā)現(xiàn)新的 Tag:  " + ++mCount + "\n");// mCount 計(jì)數(shù)
        String intentActionStr = intent.getAction();// 獲取到本次啟動(dòng)的action
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intentActionStr)// NDEF類型
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intentActionStr)// 其他類型
                || NfcAdapter.ACTION_TAG_DISCOVERED.equals(intentActionStr)) {// 未知類型

            // 在intent中讀取Tag id
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            byte[] bytesId = tag.getId();// 獲取id數(shù)組

//            info += ByteArrayChange.ByteArrayToHexString(bytesId) + "\n";
//            tv2.setText("標(biāo)簽UID:  " + "\n" + info);

            // 讀取存儲信息
//            if (mRead.isChecked()) {
//                // mChange=false;
//                tv3.setText("讀取成功! " + readTag(tag));
//                // readNfcVTag(tag);
//                etSector.setText("");
//                etBlock.setText("");
//                etData.setText("");
//            }

            // 寫數(shù)據(jù)
            if (ifWrite) {
                if (samCode.length() < 16){
                    for (int i = samCode.length(); i < 16; i++) {
                        samCode+=" ";
                    }
                }
                writeTag(tag, samCode);
            }

            // 轉(zhuǎn)換為ASCll
//            if (mChange.isChecked()) {
//                tv3.setText(change(tag));
//                Toast.makeText(getBaseContext(), "轉(zhuǎn)換成功", Toast.LENGTH_SHORT).show();
//                etSector.setText("");
//                etBlock.setText("");
//                etData.setText("");
//            }
        }
    }

    // 寫數(shù)據(jù)
    public void writeTag(Tag tag, String str) {
        MifareClassic mfc = MifareClassic.get(tag);
        try {
            if (mfc != null) {
                mfc.connect();
            } else {
                Toast.makeText(this, "寫入失敗", Toast.LENGTH_SHORT).show();
                return;
            }
            boolean b = mfc.authenticateSectorWithKeyA(5, code);
            if (b) {
                mfc.writeBlock(4 * 5, str.getBytes());
                mfc.close();
                ToastUtil.showToast("寫入成功");
                finish();
            }
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showToast("寫入失敗");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        enableForegroundDispatch();
    }

    private void enableForegroundDispatch() {
        if (mNfcAdapter != null) {
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent,
                    mFilters, mTechLists);
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        disableForegroundDispatch();
    }

    private void disableForegroundDispatch() {
        // TODO 自動(dòng)生成的方法存根
        if (mNfcAdapter != null) {
            mNfcAdapter.disableForegroundDispatch(this);
        }
    }
}

看完上述內(nèi)容,你們對android中NFC讀寫功能的實(shí)現(xiàn)方法是怎樣的有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI