本文转自薄呵呵的文章

初始化适配器 NfcAdapter PendingIntent

Intent nfcIntent = new Intent(this, getClass()); nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); mAdapter = NfcAdapter.getDefaultAdapter(this); mPendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0); String infoText = "看下这个支持nfc吗 或者 开了没";  if (mAdapter == null) {       Toast.makeText(getApplicationContext(),       infoText, Toast.LENGTH_SHORT).show();  } 

重写onNewIntent()方法

 @Override  protected void onNewIntent(Intent intent) {  Tag tag=intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  //获取 Tag 读取 ID 得到字节数组 转字符串 转码 得到卡号(默认16进制 这请自便) Long cardNo = Long.parseLong(flipHexStr(ByteArrayToHexString(tag.getId())), 16);  // if (cardNo.toString().getBytes().length == 10) {  num = cardNo.toString();  // } else {   // 转的时候有个地方需要注意下 如果开头为零的话 会省略所以位数会改变    // num = "0" + cardNo.toString();    // }    TextView textView = (TextView) findViewById(R.id.nfc_text);    textView.setText(num);    Toast.makeText(getApplicationContext(), num, Toast.LENGTH_SHORT).show();}

息屏之类的操作

@Override public void onPause() { super.onPause();  if (mAdapter != null) {   mAdapter.disableForegroundDispatch(this);   }   } @Override public void onResume() {  super.onResume();  mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);  }

最后附上转码工具类

public class ByteArrayTohexHepler {    public static String flipHexStr(String s) {       StringBuilder result = new StringBuilder();       for (int i = 0; i <= s.length() - 2; i = i + 2) {      result.append(new StringBuilder(s.substring(i, i + 2)).reverse());  }    return result.reverse().toString();}     // 16转10进制   public static String ByteArrayToHexString(byte[] inarray) {   int i, j, in;   String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};   StringBuilder out = new StringBuilder();     for (j = 0; j < inarray.length; ++j) {    in = (int) inarray[j] & 0xff;     i = (in >> 4) & 0x0f;    out.append(hex[i]);    i = in & 0x0f;    out.append(hex[i]);    } return out.toString();  } }

大家有什么问题可以在下方留言

更多相关文章

  1. Android(安卓)编译NDK
  2. Android动态获取当前手机IP地址
  3. android文件下载
  4. android录音和得到音量
  5. android 启动第三方APP的方式
  6. Android(安卓)Wifi的使用
  7. Android(Java):滑动删除实现——重写onTouch
  8. Android学习--Android带删除按钮的ListView
  9. android 下载程序

随机推荐

  1. Mysql循环选择列并在循环中执行Insert查
  2. MySql 表管理常用的sql语句
  3. 【日记】VB.NET调用MYSQL存储过程
  4. mysql 数据库整体运行状态确认思路
  5. 忽略OR子句后的MySQL AND子句[重复]
  6. 有没有更好的方法来编写这个MySQL查询?
  7. MYSQL错误代码和消息
  8. 为什么MySQL查询优化器会选择聚集主索引
  9. mysql 事物没提交导致事物一直运行解决方
  10. 无法连接到MySQL服务器