z183052114 2017-03-20 03:40 采纳率: 100%
浏览 1399

网上找的nfc读卡的demo,我想把它放到fragment中,如何改,大神们帮帮忙啊!

public class RecordActivity extends BaseActivity {
NfcAdapter mAdapter;
IntentFilter[] mFilters;
PendingIntent mPendingIntent;
public static List recordInformations = new ArrayList();

void resolveIntent(Intent intent) {

    // 1) Parse the intent and get the action that triggered this intent
    String action = intent.getAction();
    // 2) Check if it was triggered by a tag discovered interruption.
    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
        //  3) Get an instance of the TAG from the NfcAdapter
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] extraID = tagFromIntent.getId();
        StringBuilder sb = new StringBuilder();
        for (byte b : extraID) {
            sb.append(String.format("%02X", b));
        }
        String tagID = sb.toString();
        showToast(tagID);
    }

}


String[][] mTechLists = new String[][]{new String[]{NfcA.class.getName()}};
Intent intent = getIntent();

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

    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    IntentFilter ndef1 = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    //IntentFilter ndef2 = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    mFilters = new IntentFilter[]{
            ndef1,
            //ndef2,
    };

    try {
        ndef1.addDataType("*/*");
        //ndef2.addDataType("*/*");
    } catch (IntentFilter.MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    mAdapter = NfcAdapter.getDefaultAdapter(this);

    if (getIntent() != null) {
        resolveIntent(getIntent());
    }

}

@Override
public void onResume() {
    super.onResume();
    mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
}

@Override
public void onNewIntent(Intent intent) {
    Log.i("Foreground dispatch", "Discovered tag with intent: " + intent);
    resolveIntent(intent);
}

@Override
public void onPause() {
    super.onPause();
    mAdapter.disableForegroundDispatch(this);
}

}

  • 写回答

1条回答 默认 最新

  • 代码的灵魂是bug! 2017-03-20 03:51
    关注

    把代码copy进去,如果有错就改错

    评论

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集