react-native调用nfc读写cpu卡、m1卡-android篇

之前对nfc对cpu卡的操作这块,走了许多弯路,所以写下这篇文章。一方面做下总结,另一方面希望能帮助到一些人。
本文目的在于让读者了解如何在android的程序开发中对接cpu卡、m1卡,对于nfc和cpu卡、m1卡本身的技术原理不做探讨,读者可自行百度。

android对cpu卡、m1卡的识别

1、设置权限

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

2、设置感兴趣的技术列表

public NfcModel(Activity activity, Class<? extends TagTechnology>...techs){
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
            techLists =  new String[techs.length][];
            for(int i=0; i < techs.length; ++i){
                techLists[i] = new String[]{  techs[i].getName()   };
            }
            this.techs = techs;
            try{
                filters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") };
            }catch (IntentFilter.MalformedMimeTypeException e){
                throw new  RuntimeException(e);
            }
            nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
            pendingIntent = PendingIntent.getActivity(
                    activity,
                    0,
                    new Intent( activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            onNewIntent(activity.getIntent());
        }
    }

3、读取数据

 public void load(Parcelable parcelable) {
        final Tag tag = (Tag) parcelable;
        if(listener!=null){
            /**
             * 这里一定要关闭一下,防止因程序原因导致未关闭
             */
            close();

            for(Class<? extends  TagTechnology> t : techs){
                try {
                    Method method = t.getMethod("get",Tag.class);
                    TagTechnology result = (TagTechnology) method.invoke(null,tag);
                    if(result==null){
                        continue;
                    }
                    technology = result;
                    listener.onNfcEvent(result);
                } catch (Exception e) {
                    if(NfcUtil.debug){
                        throw new RuntimeException("回调nfc事件发生错误",e);
                    }else{
                        //生产环境
                        e.printStackTrace();
                    }
                }
            }
        }
    }

4、在activity中调用


public class NfcTestActivity extends AppCompatActivity implements NfcListener {

    private NfcModel nfcModel;

    private TextView result;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc);
        result = (TextView) findViewById(R.id.result);

        //
        nfcModel = new NfcModel( this, IsoDep.class, MifareClassic.class);
        nfcModel.setListener(this);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        nfcModel.onNewIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        nfcModel.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        nfcModel.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        nfcModel.destroy();
    }

    @Override
    public void onNfcEvent(TagTechnology tag) {
        try{
            tag.connect();
            if(tag instanceof IsoDep){
                DepTagAdapter adapter = new DefaultDepTagAdapter((IsoDep) tag);
                String[] results = adapter.send(new String[]{"00a40000023f00"});
                result.setText("cpu:"+results[0]);
            }else{
                MifareOneTagAdapter adapter = new DefaultMifareOneTagAdapter((MifareClassic) tag);
                adapter.authenticateSectorWithKeyA(0, HexUtil.decodeHex("A0A1A2A3A4A5"));
                byte[] bytes = adapter.readBlock(0);
                result.setText("m1:"+HexUtil.encodeHexStr(bytes));
            }
        }catch (IOException e){
            Toast.makeText(this,"请重新贴卡",Toast.LENGTH_SHORT);
        }catch (NfcException e){
            result.setText("error:"+e.getMessage());
        }

    }
}

贴卡调用app

1、使用权限

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

2、在需要贴卡后直接调用的activity中增加如下配置:

···

<activity
android:name=".MainActivity">

      <intent-filter>
          <action android:name="android.nfc.action.TAG_DISCOVERED" />
          <category android:name="android.intent.category.DEFAULT" />
      </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>

···

nfc_tech_filter内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <tech-list>
        <tech>android.nfc.tech.IsoDep</tech>
        <tech>android.nfc.tech.MifareClassic</tech>
    </tech-list>
</resources>

进行react-native封装

···

protected DepTagAdapter cpu;
protected MifareOneTagAdapter m1;

public static final String CPU = "cpu";

protected NfcModel model;

public NfcModule(ReactApplicationContext reactContext) {
    super(reactContext);
    reactContext.addLifecycleEventListener(this);
    reactContext.addActivityEventListener(this);
}

@Override
public String getName() {
    return "NfcModule";
}


@ReactMethod
public void close(){
    if(cpu !=null){
        cpu.close();
        cpu = null;
    }
    if(m1!=null){
        m1.close();
        m1 = null;
    }
}


@ReactMethod
public void isAvailable(Callback callback){
    callback.invoke(NfcUtil.isAvailable(getCurrentActivity()));
}


/**
 * m1卡写卡流程
 *
 * 参数格式为
 *
 * [
 *
 * {
 *     cmd:'write',
 *     data:'',
 *     keyb:'',
 *     sector:0
 * },
 * {
 *     cmd:'inc',
 *     data: 1,
 *     keyb:'',
 *     sector:1,
 * },
 * {
 *     cmd:'dec',
 *     data: 1,
 *     keyb:'',
 *     sector:1,
 * },
 * {
 *     cmd:'transfer',
 *     data: 1,
 *     keyb:'',
 *     sector:1,
 * }
 *
 *
 * ]
 *
 *
 *
 */
@ReactMethod
public void write(ReadableArray command, Promise promise){
    if(m1 ==null){
        promise.reject("io","closed");
        return;
    }
}

/**
 * 恢复流程
 * @param command
 * @param promise
 *
 *
 *  参数格式为
 *
 * [
 *
 *
 *  恢复流程中的拷贝
 * {
 *     cmd:'copy',
 *     src:1,           //blockIndex
 *     dest:2           //blockIndex
 *     keya:''
 * },
 *
 *  恢复流程中的恢复
 * {
 *     cmd:'restore',
 *     src:1,           //blockIndex
 *     dest:2           //blockIndex
 *     keya:''
 * },
 *
 * 恢复流程中的设置
 *
 * {
 *     cmd:'set',
 *     dest:2,           //blockIndex
 *     data:'',
 *     keya:'',
 * },
 * ]
 */
@ReactMethod
public void restore(ReadableArray command, Promise promise){
    if(m1 ==null){
        promise.reject("io","closed");
        return;
    }
}

@ReactMethod
public void readBlock(ReadableArray command, Promise promise){
    //传输进来的格式为: [  "keya0", null, "keya1",...   ]
    if(m1 ==null){
        promise.reject("io","closed");
        return;
    }

    try {
        m1.connect();
        WritableArray arr = Arguments.createArray();
        for(int i=0 , c = command.size(); i < c; ++i){
            try{
                if(command.isNull(i)){
                    arr.pushNull();
                    continue;
                }
                String cmd = command.getString(i);
                m1.authenticateSectorWithKeyA(i, HexUtil.decodeHex(cmd));
                byte[] bytes = m1.readBlock(i);
                arr.pushString( HexUtil.encodeHexStr(bytes) );
            }catch (IOException e){
                promise.reject("io",e);
                return;
            }
        }
        promise.resolve(arr);
    } catch (IOException e) {
        promise.reject("io",e);
    }

}

@ReactMethod
public void apdu(ReadableArray command, Promise promise){
    if(cpu ==null){
        promise.reject("io","closed");
        return;
    }
    try {
        cpu.connect();
        WritableArray arr = Arguments.createArray();
        for(int i=0 , c = command.size(); i < c; ++i){
            try{
                String cmd = command.getString(i);
                if(cmd.contains(",")){
                    String[] args = cmd.split(",");
                    NfcResponse response = null;
                    for(String arg : args){
                        response = cpu.send(arg);
                    }
                    //只用最后一个为主
                    String result = response.getStr();
                    arr.pushString(result);
                }else{
                    NfcResponse response = cpu.send(command.getString(i));
                    String result = response.getStr();
                    arr.pushString(result);
                }
            }catch (IOException e){
                promise.reject("io",e);
                return;
            }catch (NfcException e){
                promise.reject("nfc",e);
                return;
            }
        }
        promise.resolve(arr);
    } catch (IOException e) {
        promise.reject("io",e);
    }
}

@Override
public void onHostResume() {
    if(model==null){
        model = new NfcModel(getCurrentActivity(), IsoDep.class, MifareClassic.class);
        model.setListener(this);
    }
    model.onResume(getCurrentActivity());
}

@Override
public void onHostPause() {
    if(model!=null)
        model.onPause(getCurrentActivity());
}

@Override
public void onHostDestroy() {
    if(model!=null){
        model.destroy();
        model = null;
    }
}

@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {

}

@Override
public void onNewIntent(Intent intent) {
    if(model!=null)
        model.onNewIntent(intent);
}




@Override
public void onNfcEvent(TagTechnology tag) {

    if(tag instanceof  IsoDep){
        cpu = new DefaultDepTagAdapter( (IsoDep)tag);
        //通知感知到了
        notifyEvent("nfcTag","cpu");
    }else if(tag instanceof MifareClassic){
        m1 = new DefaultMifareOneTagAdapter( (MifareClassic)tag ) ;
        notifyEvent("nfcTag","m1");
    }

}





protected void notifyEvent(String eventName,@Nullable Object data){
    getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName,data);
}

···

源码

https://github.com/jzoom/jzoom-nfc

参考文献

Android NFC识别CPU卡和m1卡

android m1卡读写

CPU卡相关资料收集总结

android通过NFC读取公交卡的余额和交易记录

简单apdu指令返回局分析

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容