基于Android NFC传感器读取身份证信息demo

摘要:通过导入开发包sdk开发基几Android NFC设备读取身份证信息

1. 开发条件:

    1)鱼住往来科技的身份验证sdk :下载地址:https://www.yzfuture.cn/views/service/index.html

    2)Android Studio3.0以上

    3)基于java语言开发,非kotlin语言

2.添加包步骤:

1)添加以下两个包

在Android  Studio项目 中相应的依赖文件build.gradle(Module.app)添加包的依赖

文件:build.gradle(Module.app):

PS:android 需要28 的sdk一下:

android {
    compileSdkVersion 28
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.example.id_test"
        minSdkVersion 26
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        ndk {
            abiFilters 'armeabi-v7a', 'arm64-v8a','x86', 'x86_64'
        }
        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath = true
            }
        }
    }

    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
    repositories{
        flatDir{
            dirs 'libs'
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])

    implementation(name:'yzwlnfcreadcard', ext:'aar')

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment:2.3.0'
    implementation 'androidx.navigation:navigation-ui:2.3.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

 

添加好相应的依赖后,gradle一下,就可以引用相应的包了

2)AndroidMainifest.xml 文件添加相应的权限:

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

    <uses-permission android:name="android.permission.NFC" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.WRITE_SETTINGS"
        tools:ignore="ProtectedPermissions"/>

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.hardware.camera" />
    <uses-permission android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">


        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <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>
相应的资源文件:res/xmlnfc_tech_filter.xml——NFC过滤器文件:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
   <tech-list>
      <tech>android.nfc.tech.IsoDep</tech>
      <tech>android.nfc.tech.MifareClassic</tech>
      <tech>android.nfc.tech.NfcA</tech>
   </tech-list>
   <tech-list>
      <tech>android.nfc.tech.IsoDep</tech>
      <tech>android.nfc.tech.NfcB</tech>
        <tech>android.nfc.tech.NfcA</tech>
   </tech-list>

</resources>

 

注意:其中添加了一种NFC过滤器触发Intent——当NFC感应到过滤器范围中的Card类型时,会触发Intent,并执行一个Activity。

3)app流程

                                                             

Main.java相应的代码

public class MainActivity extends AppCompatActivity implements ActiveCallBack {

    private OTGReadCardAPI ReadCardAPI = null;
    private NfcAdapter nfcAdapter = null;

    private String mName = null;
    private String mIDNO = null;
    private int mSex;
    private PendingIntent pi = null;
    private IntentFilter tagDetected = null;
    private String[][] mTechLists;

    private NfcAdapter mAdapter = null; // 定义NFC适配器

    private Intent inintent = null;

    TextView tv_name, tv_sex, tv_idno;
    Button bt_act;

    private boolean bTestServer = false;
    private boolean bNFC = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_main);


        tv_name = findViewById(R.id.name);
        tv_sex = findViewById(R.id.sex);
        tv_idno = findViewById(R.id.IDNO);
        bt_act = findViewById(R.id.bt_action);



        init();//初始化NFC读卡器


//       String m_szAppKey = getSharedPreferences("appConfig",MODE_PRIVATE).getString("AppKey", "");

//        ReadCardAPI = new OTGReadCardAPI(getApplicationContext(), this, bNFC);

//        bt_act.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
                nfcRead(getIntent()); //NFC读信息
                new MyTask().execute(); //启动线程
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        nfcRead(getIntent());
                    }
                });
//            }
//
//        });

        PermissionUtil.grantNeedPermission(this); //添加权限


    }

    public void nfcRead(Intent intent) {
        /**5445454225474
         * NFC读卡过程
         *
         * */
//        ReadCardAPI = new OTGReadCardAPI(getApplicationContext(), this, false);
//        //配置服务器
//        ArrayList<Serverinfo> twoCardServerlist = new ArrayList<Serverinfo>();
//        twoCardServerlist.add(new Serverinfo("id.yzfuture.cn", 8848));  // TygerZH server测试
//        ReadCardAPI.setServerInfo(twoCardServerlist, null, bTestServer);
//        //读卡
//        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
//        if (nfcAdapter == null) {
//            Toast.makeText(this, "暂不支持NFC功能", Toast.LENGTH_LONG).show();
//            return;
//        }
//        if (nfcAdapter != null && !nfcAdapter.isEnabled()) {
//            Toast.makeText(this, "请在系统设置中先启用NFC功能", Toast.LENGTH_LONG).show();
//            finish();
//            return;
//        }

        String AppKey = "A2E91A7BF13C75AADB0400B8701FD284"; // 手机号码注册返回的数据AppKey

        int code = ReadCardAPI.NfcReadCard(AppKey, null, intent, eCardType.eTwoGeneralCard, "", false);

        int erro_code = ReadCardAPI.GetErrorCode();
        if (code == 90) {
            //解码成功
            //获取信息
            mName = ReadCardAPI.GetTwoCardInfo().szTwoIdName;
            mIDNO = ReadCardAPI.GetTwoCardInfo().szTwoIdNo;
            mSex = ReadCardAPI.GetTwoCardInfo().nTwoIdSex;

            tv_name.setText("");
            tv_sex.setText("");
            tv_idno.setText("");

            tv_name.setText(mName);
            tv_sex.setText(mSex);
            tv_idno.setText(mIDNO);

        } else {
            //解码失败
            Toast.makeText(this, "解码失败" + code + ":" + erro_code, Toast.LENGTH_LONG).show();
        }

    }

    public void init() {
        ReadCardAPI = new OTGReadCardAPI(getApplicationContext(), this, bNFC);

        ArrayList<Serverinfo> twoCardServerlist = new ArrayList<Serverinfo>();

        twoCardServerlist.add(new Serverinfo("id.yzfuture.cn", 8848));  // TygerZH server测试
        ReadCardAPI.setServerInfo(twoCardServerlist, null, bTestServer);
        mAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
        if (mAdapter != null) {
            init_NFC();
        } else {
            if (ReadCardAPI != null) {
                Toast.makeText(this, "本机不支持NFC功能", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void init_NFC() {
        pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
                .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);//.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        mTechLists = new String[][]{new String[]{NfcB.class.getName()}, new String[]{NfcA.class.getName()}};
        if (mAdapter != null && !mAdapter.isEnabled()) {
            Toast.makeText(this, "NFC尚未开启", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void setUserInfo(String s) {
    }

    @Override
    public void DeviceOpenFailed(boolean b, boolean b1) {

    }

    @Override
    public void readProgress(int nprocess) {

        Message msg = Message.obtain();
        msg.what = 0;
        msg.arg1 = nprocess;
//        mHandler.sendMessageDelayed(msg, 0);
        Log.e("aa", "  " + nprocess);
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mAdapter != null) {
            mAdapter.enableForegroundDispatch(this, pi, new IntentFilter[]{tagDetected}, mTechLists);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAdapter != null) {
            mAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    protected void onDestroy() {
//        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        inintent = intent;
//        progressBar.setProgress(0);
        nfcRead(intent);
    }
}

 

 

更新中........

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值