NFC打开指定应用 URI实现

这段代码展示了如何使用NFC技术创建一个NdefRecord,然后写入到NFC标签中,以在读取标签时启动指定的URI('zoeice://com.zoeice.example/applicationUp')。代码首先检查标签是否可写,然后尝试写入NDEF消息。如果标签已格式化,直接写入;否则,先格式化再写入。在写入过程中,处理了各种可能的异常,如TagLostException、IOException和FormatException。
摘要由CSDN通过智能技术生成
import java.io.IOException;
import java.nio.charset.Charset;

import android.content.Context;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.widget.Toast;

public class NFC {
public static boolean writeTag(Context context, Tag tag) {    
    NdefRecord relayRecord = new NdefRecord(
        NdefRecord.TNF_ABSOLUTE_URI ,
        "zoeice://com.zoeice.example/applicationUp".getBytes(Charset.forName("US-ASCII")),
       new byte[0], new byte[0]);
 
    // Complete NDEF message with both records
    NdefMessage message = new NdefMessage(new NdefRecord[] {relayRecord});
 
    try {
        // If the tag is already formatted, just write the message to it
        Ndef ndef = Ndef.get(tag);
        if(ndef != null) {
            ndef.connect();
 
            // Make sure the tag is writable
            if(!ndef.isWritable()) {
     
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值