Android 安卓NFC读取标签
在我的应用程序中,我有两个选择:写入和读取NFC标记。我正在另一个名为WriteNFC的活动中进行NFC标记写入过程。当标记进入范围时,我希望我的主要活动读取并显示标记数据。写作过程似乎还行。但是每当我试着读标签的时候。它什么也不显示Android 安卓NFC读取标签,android,nfc,Android,Nfc,在我的应用程序中,我有两个选择:写入和读取NFC标记。我正在另一个名为WriteNFC的活动中进行NFC标记写入过程。当标记进入范围时,我希望我的主要活动读取并显示标记数据。写作过程似乎还行。但是每当我试着读标签的时候。它什么也不显示 public class MainActivity extends Activity { public static int id = 1; public static int bakiye = 5; public static Context myContex
public class MainActivity extends Activity {
public static int id = 1;
public static int bakiye = 5;
public static Context myContext;
public static boolean availableForRead = true;
private Button myButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), nfcWrite.class);
startActivity(i);
}
});
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onNewIntent(Intent intent) {
System.out.println("Intent detected");
if (intent.getType() != null && intent.getType().equals("application/" + getPackageName())) {
// Read the first record which contains the NFC data
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefRecord relayRecord = ((NdefMessage) rawMsgs[0]).getRecords()[0];
String nfcData = new String(relayRecord.getPayload());
System.out.println("Reading Process is Complete...");
// Display the data on the tag
Toast.makeText(this, nfcData, Toast.LENGTH_SHORT).show();
}
}
}
以下是我的nfcWrite活动:
package com.example.nfchandler;
import java.io.IOException;
import java.nio.charset.Charset;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.widget.Toast;
public class nfcWrite extends Activity {
private int id = 1;
private int balance = 5;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nfc_write);
}
@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String nfcMessage = intent.getStringExtra("nfcMessage");
if(nfcMessage != null) {
writeTag(this, tag, nfcMessage);
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
setupIntent();
}
public void setupIntent() {
String nfcMessage = id + "-" + balance;
// When an NFC tag comes into range, call the main activity which
// handles writing the data to the tag
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
Intent nfcIntent = new Intent(this, nfcWrite.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
nfcIntent.putExtra("nfcMessage", nfcMessage);
PendingIntent pi = PendingIntent.getActivity(this, 0, nfcIntent, PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
nfcAdapter.enableForegroundDispatch((Activity) this, pi, new IntentFilter[] { tagDetected }, null);
}
public boolean writeTag(Context context, Tag tag, String data) {
// Record to launch Play Store if app is not installed
NdefRecord appRecord = NdefRecord.createApplicationRecord(context.getPackageName());
// Record with actual data we care about
NdefRecord relayRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
new String("application/" + context.getPackageName()).getBytes(Charset.forName("US-ASCII")),
null, data.getBytes());
// Complete NDEF message with both records
NdefMessage message = new NdefMessage(new NdefRecord[] { relayRecord, appRecord });
try {
// If the tag is already formatted, just write the message to it
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
// Make sure the tag is writable
if (!ndef.isWritable()) {
Toast.makeText(getApplicationContext(), "Etiket yazılabilir değil", Toast.LENGTH_SHORT).show();
return false;
}
// Check if there's enough space on the tag for the message
int size = message.toByteArray().length;
if (ndef.getMaxSize() < size) {
Toast.makeText(getApplicationContext(), "Etikette yeterli alan yok...", Toast.LENGTH_SHORT).show();
return false;
}
try {
// Write the data to the tag
ndef.writeNdefMessage(message);
Toast.makeText(getApplicationContext(), "Bilgileri yazma başarılı...", Toast.LENGTH_SHORT).show();
return true;
} catch (TagLostException tle) {
return false;
} catch (IOException ioe) {
return false;
} catch (FormatException fe) {
return false;
}
// If the tag is not formatted, format it with the message
} else {
NdefFormatable format = NdefFormatable.get(tag);
if (format != null) {
try {
format.connect();
format.format(message);
return true;
} catch (TagLostException tle) {
return false;
} catch (IOException ioe) {
return false;
} catch (FormatException fe) {
return false;
}
} else {
return false;
}
}
} catch (Exception e) {
}
return false;
}
}
package com.example.nfchandler;
导入java.io.IOException;
导入java.nio.charset.charset;
导入android.app.Activity;
导入android.app.pendingent;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.nfc.FormatException;
导入android.nfc.NdefMessage;
导入android.nfc.NdefRecord;
导入android.nfc.NfcAdapter;
导入android.nfc.Tag;
导入android.nfc.TagLostException;
导入android.nfc.tech.Ndef;
导入android.nfc.tech.n可验证;
导入android.os.Bundle;
导入android.widget.Toast;
公共类nfcWrite扩展活动{
私有int id=1;
私人国际收支平衡=5;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.nfc_write);
}
@凌驾
受保护的void onNewIntent(意图){
//TODO自动生成的方法存根
super.onNewIntent(意向);
Tag Tag=intent.getParcelableExtra(NfcAdapter.EXTRA_Tag);
字符串nfcMessage=intent.getStringExtra(“nfcMessage”);
if(nfcMessage!=null){
writeTag(this、tag、nfcMessage);
}
}
@凌驾
受保护的void onResume(){
//TODO自动生成的方法存根
super.onResume();
setupIntent();
}
公共目的(){
字符串nfcMessage=id+“-”+余额;
//当NFC标签进入范围时,调用
//处理将数据写入标记的操作
NfcAdapter NfcAdapter=NfcAdapter.getDefaultAdapter(此);
Intent nfcIntent=newintent(这是nfcWrite.class).addFlags(Intent.FLAG\u ACTIVITY\u SINGLE\u TOP);
nfcIntent.putExtra(“nfcMessage”,nfcMessage);
PendingEvent pi=PendingEvent.getActivity(this,0,nfcIntent,PendingEvent.FLAG_UPDATE_CURRENT);
IntentFilter tagDetected=新的IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
nfcAdapter.enableForegroundDispatch((活动)this,pi,newintentfilter[]{tagDetected},null);
}
公共布尔writeTag(上下文、标记、字符串数据){
//如果未安装应用程序,录制以启动Play Store
NdefRecord appRecord=NdefRecord.createApplicationRecord(context.getPackageName());
//记录我们关心的实际数据
NdefRecord relayRecord=新的NdefRecord(NdefRecord.TNF\u MIME\u媒体,
新字符串(“application/”+context.getPackageName()).getBytes(Charset.forName(“US-ASCII”)),
null,data.getBytes());
//用两条记录完成NDEF消息
NdefMessage message=新的NdefMessage(新的NdefRecord[]{relayRecord,appRecord});
试一试{
//如果标签已经格式化,只需将消息写入其中
Ndef Ndef=Ndef.get(标签);
如果(ndef!=null){
connect();
//确保标记是可写的
如果(!ndef.isWritable()){
Toast.makeText(getApplicationContext(),“Etiket yazılabilir değil”,Toast.LENGTH_SHORT).show();
返回false;
}
//检查标签上是否有足够的空间放置邮件
int size=message.toByteArray().length;
if(ndef.getMaxSize()
以下代码解决了我的问题:
Intent intent=getIntent();
NdefMessage[] msgs;
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefRecord relayRecord = ((NdefMessage)rawMsgs[0]).getRecords()[0];
String nfcData = new String(relayRecord.getPayload());
Toast.makeText(getApplicationContext(),nfcData,Toast.LENGTH_LONG).show();
}
以下代码解决了我的问题:
Intent intent=getIntent();
NdefMessage[] msgs;
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefRecord relayRecord = ((NdefMessage)rawMsgs[0]).getRecords()[0];
String nfcData = new String(relayRecord.getPayload());
Toast.makeText(getApplicationContext(),nfcData,Toast.LENGTH_LONG).show();
}
以下代码解决了我的问题:
Intent intent=getIntent();
NdefMessage[] msgs;
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefRecord relayRecord = ((NdefMessage)rawMsgs[0]).getRecords()[0];
String nfcData = new String(relayRecord.getPayload());
Toast.makeText(getApplicationContext(),nfcData,Toast.LENGTH_LONG).show();
}
以下代码解决了我的问题:
Intent intent=getIntent();
NdefMessage[] msgs;
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefRecord relayRecord = ((NdefMessage)rawMsgs[0]).getRecords()[0];
String nfcData = new String(relayRecord.getPayload());
Toast.makeText(getApplicationContext(),nfcData,Toast.LENGTH_LONG).show();
}
您的代码在NFC功能方面有几个问题:
onNewIntent
方法中检查NFC相关意图。但是,onNewIntent
方法仅在特定条件下调用。例如,在活动初始开始时,不会被调用(例如,由于被清单中的意图过滤器触发)。在这种情况下,您需要在onCreate中处理接收到的意图