您的位置:首页 > 移动开发 > Android开发

Android读取NFC卡的编号

2014-08-13 18:03 253 查看
NFC相关androidManifest文件设置:

一、权限:<uses-permission android:name="android.permission.NFC"/>

二、sdk级别限制:<uses-sdk android:minSdkVersion="10"/>

三、特殊功能限制<uses-feature android:name="android.hardware.nfc" android:required="true" />这个生命可以让你的应用在google play上被声明使用者必须拥有nfc功能。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nfc"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.NFC" />

    <uses-feature
        android:name="android.hardware.nfc"
        android:required="true" />

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:launchMode="singleTask"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.nfc.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            
            <intent-filter>
                <action android:name="android.nfc.action.TECH_DISCOVERED" />
            </intent-filter>

            <meta-data
                android:name="android.nfc.action.TECH_DISCOVERED"
                android:resource="@xml/nfc_tech_filter" />

        </activity>
    </application>

</manifest>
上面的android:resource="@xml/nfc_tech_filter"是对tech类型的过滤条件,在res文件夹新建一个xml文件夹,新建nfc_tech_filter.xml文件。

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <tech-list>
        <tech>android.nfc.tech.IsoDep</tech>
        <tech>android.nfc.tech.NfcA</tech>        
        <tech>android.nfc.tech.NfcB</tech>
        <tech>android.nfc.tech.NfcF</tech>
        <tech>android.nfc.tech.NfcV</tech>
        <tech>android.nfc.tech.Ndef</tech>
        <tech>android.nfc.tech.NdefFormatable</tech>
        <tech>android.nfc.tech.MifareClassic</tech>
        <tech>android.nfc.tech.MifareUltralight</tech>
    </tech-list>
</resources>


下面是封装了读取NFC卡号的一个类:

需要注意的是,上面配置文件中有一个“ android:launchMode="singleTask"”,这是设置应用为单任务。代码中的getId(Intent intent)必须要在Activity的onNewIntent(Intent intent)中执行。因为系统检测到NFC卡的时候,会自动生成封装了相应Tag的Intent,当应用在接收到Intent的时候,默认情况下是启动自己的Activity,这样就会致使每次接收到Intent都会启动新的Activity。把应用设置为单任务后,就可以避免这种情况的发生。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: