我正在尝试使用NFC开始编写应用程序。我只需要从一部手机发送NDef消息到另一部手机只包含一个简单的字符串。
我的传输活动:
public class MainActivity extends Activity {
NfcAdapter mNfcAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
NdefMessage msg = new NdefMessage(
new NdefRecord[] { createTextRecord("Bla", Locale.GERMANY , true )});
mNfcAdapter.setNdefPushMessage(msg, this);
}
public NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) {
byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
byte[] textBytes = payload.getBytes(utfEncoding);
int utfBit = encodeInUtf8 ? 0 : (1 << 7);
char status = (char) (utfBit + langBytes.length);
byte[] data = new byte[1 + langBytes.length + textBytes.length];
data[0] = (byte) status;
System.arraycopy(langBytes, 0, data, 1, langBytes.length);
System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT, new byte[0], data);
return record;
}
}
然后我只是尝试在另一部手机上收到一些意图发生的意图:
public class MainActivity extends Activity {
NfcAdapter mNfcAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Toast.makeText(getApplicationContext(), "Received an Event onResume", Toast.LENGTH_LONG).show();
}
}
}
可悲的是,如果我点按手机就没有任何反应。谢谢你的帮助!
答案 0 :(得分:2)
On Their website。您应该首先查看文档。
本文档介绍了您在Android中执行的基本NFC任务。它 解释了如何以NDEF消息的形式发送和接收NFC数据 并描述了支持这些功能的Android框架API。 有关更高级的主题,包括使用的讨论 非NDEF数据,请参阅高级NFC。