Android NFC isodep 读写
时间: 2023-08-30 16:04:22 浏览: 68
Android NFC技术中的ISO-DEP协议(ISO 14443-4)提供了一种在NFC标签和Android设备之间进行读写通信的方式。以下是一个简单的ISO-DEP读写示例,您可以参考其中的代码实现。
首先,您需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.NFC"/>
```
然后,在您的Activity类中,实现以下代码:
```java
private NfcAdapter mAdapter;
private PendingIntent mPendingIntent;
private IsoDep mIsoDep;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = NfcAdapter.getDefaultAdapter(this);
// 创建一个PendingIntent对象,用于在检测到标签时启动Activity
mPendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
@Override
protected void onResume() {
super.onResume();
// 检测NFC是否可用
if (mAdapter == null) {
Toast.makeText(this, "NFC不可用", Toast.LENGTH_LONG).show();
return;
}
// 当前Activity在前台时,启动前台调度系统以检测标签
mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
}
@Override
protected void onPause() {
super.onPause();
// 当前Activity不再处于前台时,停止前台调度系统
mAdapter.disableForegroundDispatch(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// 检测到标签时,获取IsoDep对象
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
mIsoDep = IsoDep.get(tag);
}
// 如果获取到IsoDep对象,可以进行读写操作
if (mIsoDep != null) {
try {
mIsoDep.connect();
byte[] data = mIsoDep.transceive(new byte[] {0x00, 0x01, 0x02, 0x03}); // 发送一个命令并接收响应
Log.d("ISO-DEP", "读取到的数据:" + Arrays.toString(data));
mIsoDep.close();
} catch (IOException e) {
Log.e("ISO-DEP", "连接失败", e);
}
}
}
```
在这个示例中,我们使用了Android的前台调度系统来检测标签,并通过IsoDep对象进行读写操作。在onNewIntent()方法中,我们获取到IsoDep对象后,可以使用connect()方法连接标签,使用transceive()方法进行数据交换,最后使用close()方法关闭连接。
以上是一个简单的ISO-DEP读写示例,您可以根据自己的需求进行修改和扩展。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)