NFC在Android中的应用
2016-03-19 00:09
453 查看
什么是NFC?Google一大坨,百度一大坨,我就不讲了,这里我只讨论技术细节。
首先我们先讨论一下这样的一个问题,当我们把NFC标签靠近手机,并且手机感应后,我们通过什么方式能得到NFC标签信息呢?答案就是通过Intent的方式来获取。现在的需求是我想在启动一个Activity后通过读NFC的方式得到里面的信息。下面我来介绍具体做法。
通过分析需求得知,我们需要前台调度系统机制,这种机制允许Activity拦截Intent对象。
1.获取NfcAdapter
2.构造PendingInent对象封装NFC标签信息
3.声明Intent对象的过滤器
4.建立一个处理NFC标签技术的数组
5.这是最核心最重要的一步了,我们需要在Activity的onResume方法中调用nfcadapter的enableForegroundDispatch方法把上面的变量作为参数传递进来,
一旦NFC标签接触到手机,这个方法就会被激活。
6.最后我们需要在onNewIntent方法中处理Intent回调给我们的信息。
首先我们先讨论一下这样的一个问题,当我们把NFC标签靠近手机,并且手机感应后,我们通过什么方式能得到NFC标签信息呢?答案就是通过Intent的方式来获取。现在的需求是我想在启动一个Activity后通过读NFC的方式得到里面的信息。下面我来介绍具体做法。
通过分析需求得知,我们需要前台调度系统机制,这种机制允许Activity拦截Intent对象。
1.获取NfcAdapter
nfcAdapter= NfcAdapter.getDefaultAdapter(this);
2.构造PendingInent对象封装NFC标签信息
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
3.声明Intent对象的过滤器
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);try { ndef.addDataType("*/*");} catch (IntentFilter.MalformedMimeTypeException e) { throw new RuntimeException("fail", e); }
4.建立一个处理NFC标签技术的数组
mTechLists = new String[][]{new String[]{NfcF.class.getName()}};
5.这是最核心最重要的一步了,我们需要在Activity的onResume方法中调用nfcadapter的enableForegroundDispatch方法把上面的变量作为参数传递进来,
nfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,mTechLists);
一旦NFC标签接触到手机,这个方法就会被激活。
6.最后我们需要在onNewIntent方法中处理Intent回调给我们的信息。
Parcelable[] rawArray = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);NdefMessage mNdefMsg = (NdefMessage) rawArray[0];//得到NdefMessageNdefRecord mNdefRecord = mNdefMsg.getRecords()[0];//得到NdefRecord
相关文章推荐
- android点击事件分发
- android 权重
- Android五种数据存储方式
- Android studio下的SerialPort开发
- android学习笔记——监听器
- Android 从setContentView谈Activity界面的加载过程
- android jni socket
- android ToolBar + SearchView
- Android分类块图片自适应宽度。
- Android TextView的使用
- android 权重
- 安卓自定义组件及其操控
- Android Butter Knife 框架——最好用的View注入
- andorid studio 启动 fetching android sdk..问题解决办法
- Android+PHP+MYSQL开发简单实例
- 如何获取 Android 设备的CPU核数、时钟频率以及内存大小
- Android常用权限permission列表摘录
- Error inflating class android.widget.CheckBox
- Android为CustomView在xml中设置属性
- Android 全屏显示