Android 方法NdefRecord.createTextRecord(“en”和“string”)在API级别21以下不起作用
当我在带有Android棒棒糖(5.x)或棉花糖(6.0)的设备上使用该代码时,该代码运行良好:Android 方法NdefRecord.createTextRecord(“en”和“string”)在API级别21以下不起作用,android,nfc,backwards-compatibility,ndef,Android,Nfc,Backwards Compatibility,Ndef,当我在带有Android棒棒糖(5.x)或棉花糖(6.0)的设备上使用该代码时,该代码运行良好: 但当我在安卓4.2.2(API级别17)设备上尝试这一功能时,我的应用程序崩溃了。如何使用此代码在低于21的API级别上创建文本记录(即方法NdefRecord.createTextRecord可用的API级别)?是的,在API 21中引入了createTextRecord,因此在以前的版本中无法调用它。 在调用createTextRecord之前,请检查API级别是否为21 public Ndf
但当我在安卓4.2.2(API级别17)设备上尝试这一功能时,我的应用程序崩溃了。如何使用此代码在低于21的API级别上创建文本记录(即方法
NdefRecord.createTextRecord
可用的API级别)?是的,在API 21中引入了createTextRecord,因此在以前的版本中无法调用它。
在调用createTextRecord之前,请检查API级别是否为21
public NdfeMessage create(String content){
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
NdefRecord record = NdefRecord.createTextRecord("en", content);
NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
return msg;
} else{
return null;
}
}
API级别21中引入了方法
NdefRecord.createTextRecord()
。因此,它在低于该API级别的平台上不可用。但是,您可以自己轻松地组装文本记录。文本记录的有效负载由状态字节、语言代码字段和文本字段组成:
+-------------+---------------+--------------------------+
| Status byte | Language code | Text |
| (1 byte) | (n byte) | (m byte) |
+-------------+---------------+--------------------------+
但是我还想从api级别21以下的设备写入纯文本。您可以从api级别10写入消息,但您不能在级别21下写入新记录,这是不一样的。API低于21并不意味着不能编写记录,但它意味着
NdefRecord.createTextRecord
不可用。您仍然可以按照其他答案的状态以其他方式创建它。
+-------------+---------------+--------------------------+
| Status byte | Language code | Text |
| (1 byte) | (n byte) | (m byte) |
+-------------+---------------+--------------------------+
public static NdefRecord createTextRecord(String language, String text) {
byte[] languageBytes;
byte[] textBytes;
try {
languageBytes = language.getBytes("US-ASCII");
textBytes = text.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
byte[] recordPayload = new byte[1 + (languageBytes.length & 0x03F) + textBytes.length];
recordPayload[0] = (byte)(languageBytes.length & 0x03F);
System.arraycopy(languageBytes, 0, recordPayload, 1, languageBytes.length & 0x03F);
System.arraycopy(textBytes, 0, recordPayload, 1 + (languageBytes.length & 0x03F), textBytes.length);
return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, null, recordPayload);
}
NdefRecord r = createTextRecord("en", content);