繁体   English   中英

基于主机的卡仿真或HCE

[英]Host-based Card Emulation or HCE

我想编写一个可以存储唯一ID的程序,然后将其共享为NFC标签。 我完全想编写可以使用移动设备而不是智能卡的程序。

我在许多站点和这里都读过它,但是我不明白如何将ID推送到我的应用程序以及如何通过NFC阅读器设备共享此ID

我不知道下面代码做什么,它们的功能是什么

public class MainActivity extends Activity {

  public void onCreate(Bundle savedInstanceState) {
    pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    filters = new IntentFilter[] { new IntentFilter(
                NfcAdapter.ACTION_TECH_DISCOVERED) };
    techLists = new String[][] { { "android.nfc.tech.IsoPcdA" } };
  }

  public void onResume() {
    super.onResume();
    if (adapter != null) {
      adapter.enableForegroundDispatch(this, pendingIntent, filters,
                    techLists);
    }
  }

  public void onPause() {
    super.onPause();
    if (adapter != null) {
      adapter.disableForegroundDispatch(this);
    }
  }

}

我建议阅读更多有关NFC的一般知识以及Android的ForegroundDispatcher 首先,我将在基线中描述此代码的功能。

public class MainActivity extends Activity {

  public void onCreate(Bundle savedInstanceState) {

    //Here you define an intent that will be raised when a tag is received.
    pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    //These are the tag conditions to throw the intent of above.
    //ACTION_TECH_DISCOVERED means the tag need to be of the type defined in the techlist.      
    filters = new IntentFilter[] { new IntentFilter(
                NfcAdapter.ACTION_TECH_DISCOVERED) };

    //As the name already says, this is your techlist
    techLists = new String[][] { { "android.nfc.tech.IsoPcdA" } };


  }

  public void onResume() {
    super.onResume();
    if (adapter != null) {

      //This enabled the foreground dispatching
      //It means that when a tag is detected of the type `IsoPcdA`. The `pendingIntent` will be given to the current activity
      adapter.enableForegroundDispatch(this, pendingIntent, filters,
                    techLists);
    }
  }

  public void onPause() {
    super.onPause();
    if (adapter != null) {

      //This is to disable the foreground dispatching. You don't want to send this intents to this activity when it isn't active
      adapter.disableForegroundDispatch(this);
    }
  }

}

由于此ForegroundDispatching会引发新的intent您需要覆盖onNewIntent方法。 您可以在此处读取(和写入)标签。

@Override
public void onNewIntent(Intent intent)
{
    // Get the tag from the given intent
    Tag t = (Tag)intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);   
}       

祝好运!

顺便说一句:这不是HCE! 上面的代码是读取器/写入器模式的示例,您可以在其中读取(或写入)标签。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM