android在 iButtonCallback回调里怎样取得Context上下文
时间: 2023-12-23 11:06:02 浏览: 36
在Android中,iButtonCallback回调通常是在读取NFC标签或卡片时使用的。在该回调中,可以通过传入Context参数或者使用Lambda表达式来获取Context上下文。如果使用Lambda表达式,则可以使用闭包来获取Context上下文。示例如下:
```java
public class MyNfcReader implements NfcAdapter.ReaderCallback {
private Context context;
public MyNfcReader(Context context) {
this.context = context;
}
@Override
public void onTagDiscovered(Tag tag) {
// ...
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
NdefMessage ndefMessage = ndef.getNdefMessage();
if (ndefMessage != null) {
NdefRecord[] records = ndefMessage.getRecords();
for (NdefRecord record : records) {
if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(record.getType(), NdefRecord.RTD_TEXT)) {
String text = readText(record);
// Use the context object here...
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
}
}
ndef.close();
}
// ...
}
// ...
}
```
在上面的示例中,通过在构造函数中传入Context参数或者使用Lambda表达式来获取Context上下文,然后在iButtonCallback回调中使用Context对象。请注意,如果使用Lambda表达式,则需要确保Context对象是有效的并且没有被销毁。否则,可能会引发NullPointerException等异常。