Files
ElderlyAssistant/app/src/main/java/com/ttstd/elderlyassistant/utils/WriteMessageUtils.java

46 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.ttstd.elderlyassistant.utils;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import java.io.IOException;
public class WriteMessageUtils {
public static void writePhoneToTag(Tag tag, String phoneNumber) {
// 构建tel:协议的URI
Uri uri = Uri.parse("tel:" + phoneNumber);
// 创建URI类型的NdefRecord
NdefRecord uriRecord = NdefRecord.createUri(uri);
NdefMessage message = new NdefMessage(new NdefRecord[]{uriRecord});
try {
Ndef ndef = Ndef.get(tag);
ndef.connect();
ndef.writeNdefMessage(message); // 写入NDEF消息
ndef.close();
} catch (IOException | FormatException e) {
e.printStackTrace();
}
}
public static void writeUrlToTag(Tag tag, String url) {
// 确保URL包含协议如http://
Uri uri = Uri.parse(url);
NdefRecord uriRecord = NdefRecord.createUri(uri);
NdefMessage message = new NdefMessage(new NdefRecord[]{uriRecord});
try {
Ndef ndef = Ndef.get(tag);
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
} catch (IOException | FormatException e) {
e.printStackTrace();
}
}
}