Android中NFC读写

原文链接: https://blog.csdn.net/sky2016_w/article/details/79026596

参考网址:https://blog.csdn.net/sky2016_w/article/details/79026596

https://www.jianshu.com/p/61f90708bb02

1、首先在manifests里面声明NFC和添加相应的权限;
  


2、在Activity标签中声明识别NFC标签;
  
      
          

          

          
      
3、封装NFC的读写,方便调用
public class NfcUtils {  

    //nfc  
    public static NfcAdapter mNfcAdapter;  
    public static IntentFilter[] mIntentFilter = null;  
    public static PendingIntent mPendingIntent = null;  
    public static String[][] mTechList = null;  

    /** 
     * 构造函数,用于初始化nfc
     */  
    public NfcUtils(Activity activity) {  
        mNfcAdapter = NfcCheck(activity);  
        NfcInit(activity);  
    }  

    /** 
     * 检查NFC是否打开 
     */  
    public static NfcAdapter NfcCheck(Activity activity) {  
        NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);  
        if (mNfcAdapter == null) {  
            return null;  
        } else {  
            if (!mNfcAdapter.isEnabled()) {  
                Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);  
                activity.startActivity(setNfc);  
            }  
        }  
        return mNfcAdapter;  
    }  

    /** 
     * 初始化nfc设置 
     */  
    public static void NfcInit(Activity activity) {  
        mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);  
        IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);  
        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);  
        try {  
            filter.addDataType("*/*");  
        } catch (IntentFilter.MalformedMimeTypeException e) {  
            e.printStackTrace();  
        }  
        mIntentFilter = new IntentFilter[]{filter, filter2};  
        mTechList = null;  
    }  

    /**  
     * 读取NFC的数据  
     */  
    public static String readNFCFromTag(Intent intent) throws UnsupportedEncodingException {  
        Parcelable[] rawArray = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);  
        if (rawArray != null) {  
            NdefMessage mNdefMsg = (NdefMessage) rawArray[0];  
            NdefRecord mNdefRecord = mNdefMsg.getRecords()[0];  
            if (mNdefRecord != null) {  
                String readResult = new String(mNdefRecord.getPayload(), "UTF-8");  
                return readResult;  
            }  
        }  
        return "";  
    }  


    /** 
     * 往nfc写入数据 
     */  
    public static void writeNFCToTag(String data, Intent intent) throws IOException, FormatException {  
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  
        Ndef ndef = Ndef.get(tag);  
        ndef.connect();  
        NdefRecord ndefRecord = NdefRecord.createTextRecord(null, data);  
        NdefRecord[] records = {ndefRecord};  
        NdefMessage ndefMessage = new NdefMessage(records);  
        ndef.writeNdefMessage(ndefMessage);  
    }  

    /** 
     * 读取nfcID 
     */  
    public static String readNFCId(Intent intent) throws UnsupportedEncodingException {  
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  
        String id = ByteArrayToHexString(tag.getId());  
        return id;  
    }  

    /** 
     * 将字节数组转换为字符串 
     */  
    private static String ByteArrayToHexString(byte[] inarray) {  
        int i, j, in;  
        String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};  
        String out = "";  

        for (j = 0; j < inarray.length; ++j) {  
            in = (int) inarray[j] & 0xff;  
            i = (in >> 4) & 0x0f;  
            out += hex[i];  
            i = in & 0x0f;  
            out += hex[i];  
        }  
        return out;  
    }  
}  
4、在NFCActivity代码中的使用、使用标签的前台调度系统
@Override  
public void initData() {  
    //nfc初始化设置  
    NfcUtils nfcUtils = new NfcUtils(this);  
} 

@Override  
protected void onResume() {  
    super.onResume();  
    //开启前台调度系统  
    NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);  
}
@Override  
protected void onPause() {  
    super.onPause();  
    //关闭前台调度系统  
    NfcUtils.mNfcAdapter.disableForegroundDispatch(this);  
}

@Override  
protected void onNewIntent(Intent intent) {  
    super.onNewIntent(intent);  
    //当该Activity接收到NFC标签时,运行该方法  
    //调用工具方法,读取NFC数据  
    String str = NfcUtils.rendFromTag(intent);  
}

5、判断手机是否支持NFC 
PackageManager packageManager = this.getPackageManager();
boolean b1 = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
Toast.makeText(context, "是否支持nfc:" + b1, 1).show();

 

你可能感兴趣的:(Android,Studio)