听一下我制作第一个 Nfc 应用程序的基本方法的代码大纲。我尝试替换值(我使用 nfcA 而不是 nfcV),以便您可以更好地阅读它。这是一个非常基本的结构,您需要用自己的代码填写部分内容,但它应该让您对 NFC 应用程序的结构如何工作有一个很好的了解。
public class Android_nfc_ibox extends Activity implements Runnable {
NfcAdapter mNfcAdapter;
private String[][] mTechLists;
PendingIntent pendingIntent;
Tag tag;
NfcA mTag;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize the NFC adapter
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter != null) {
dialog_text.append("Tap an NFC tag for access\n\r");
} else {
dialog_text.append("This phone is not NFC enabled\n\r");
}
// Create the PendingIntent object which will contain the details of the tag that has been scanned
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// Setup a tech list for all desired tag types
mTechLists = new String[][] { new String[] { NfcA.class.getName() } };
}
/** Re-enable the tag dispatch if the app is in the foreground */
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) mNfcAdapter.enableForegroundDispatch(this, pendingIntent, null, mTechLists);
}
/** Disable the tag dispatch when the app is no longer in the foreground */
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null) mNfcAdapter.disableForegroundDispatch(this);
}
/** A tag has been discovered */
@Override
public void onNewIntent(Intent intent){
// get the tag object for the discovered tag
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// try and get the MifareUltralight instance for this tag
mTag = NfcV.get(tag);
// if null then this wasn't a NfcV tag so wait for next time
if(mTag == null){
dialog_text.append("Not a Nfc V tag\n\r");
}
// Start the tag communications thread
Thread myThread = new Thread(this);
myThread.start();
}
}
// (we could create other threads for other types of tags)
public void run(){
// try to connect to the Nfc V tag
try{
mTag.connect();
}catch(IOException e){
//handle the error here
}
//this will send raw data
//send the values you want in the byte[]
//just add the raw hex values with commas
//pageBuffer is an array that will hold the response
try{
pageBuffer = mTag.transceive(new byte[] {0x11, 0x24, 0x11});
}catch(IOException e){
//handle error here
}
}
}