问题
Is it possible to force android to check if an NFC tag is near? I'm only able to read the tag when android detects it, I would like to force it to check if a tag is near at a specific moment
回答1:
What you want to do is in general not possible. However if you can live with a dirty hack the following will work (thanks to unspecified behaviour):
First disable the reader-mode of all supported tag types. This brings the NFC subsystem into a clean state, e.g. it makes sure that the NFC controller will have no connection to the tag.
Once done restore the reader-mode again. If a tag is present at that moment you will get the usual discovery action as an intent. It may take a second or two though.
Control of the reader-mode is possible using NfcAdapter.enableReaderMode
and NfcAdapter.disableReaderMode
回答2:
I figured out a bit of a hack for this that works (for me, at least!)
First, when you initially detect the tag via the android.nfc.action.NDEF_DISCOVERED
, get the tag as a field in your class and start a timer (this is in C#/Xamarin but the same should apply for Java):
_tag = Intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
ReaderTimer = new Timer(2000);
ReaderTimer.Elapsed += TimerElapsed;
ReaderTimer.Start();
Now, every 2 seconds this will fire. It will attempt to reconnect to the tag. If it can't the tag is gone.:
private void TimerElapsed(object sender, ElapsedEventArgs e)
{
if (_tag == null)
{
return;
}
Ndef ndef = Ndef.Get(_tag);
if (ndef == null)
{
// NDEF is not supported by this Tag.
return;
}
if (!ndef.IsConnected)
{
try
{
ndef.Close();
ndef.Connect();
}
catch (Exception ex)
{
// could not reconnect
// implies tag is not in proximity
//do whatever needs to be done when NFC is disconnected
ReaderTimer.Stop();
}
}
}
I've tested this with API 14.
Unfortunately when the screen is turned off ndef.Connect()
fails, so that is registered as a disconnect.
回答3:
Try this code and it works ! It will continuously check if the NFC tag is near to the phone or not.
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
readFromIntent(intent);
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
checkNFCStatus();
handler.postDelayed(this,1000);
}
}, 1000);
}
}
public void checkNFCStatus(){
try {
if(myTag != null) {
Ndef ndefTag = Ndef.get(myTag);
ndefTag.connect();
if (ndefTag.isConnected()) {
Log.d("network", "NFC connected");
} else {
Log.d("network", "NFC disconnected");
}
ndefTag.close();
}
} catch (IOException e) {
e.printStackTrace();
Log.d("network", "NFC disconnected");
}
}
//If the connection is not closed, an exception will be thrown
来源:https://stackoverflow.com/questions/27017813/check-if-nfc-tag-is-near