Nfcadpater.enablereadermode(...) Doesn't Work Consistently If Booting In Kiosk Mode Activity
Solution 1:
Update: may be another system App is starting after yours and taking the foreground.
I think you can force your app to Foreground just before you enable reader mode? e.g. https://stackoverflow.com/a/10019332/2373819
No idea what is going on, other than thinking it is a timing issue.
BUT two things that might help.
Try checking
NfcAdapter.isEnabled()
is true to help determine if the NFC hardware is actually available before your tryenableReaderMode
Setup a broadcaster receiver to log the NFC service states and
enableReaderMode
when it is ready as well as inonResume
.
This should be more reliable than polling to see if the adapter is available at a later time.
This can be done with the following code:-
protectedvoidonCreate(Bundle savedInstanceState) {
// All the normal onCreate Stuff// Listen for changes NFC settingsIntentFilterfilter=newIntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
this.registerReceiver(mReceiver, filter);
}
privatefinalBroadcastReceivermReceiver=newBroadcastReceiver() {
@OverridepublicvoidonReceive(Context context, Intent intent) {
finalStringaction= intent.getAction();
if (action != null && action.equals(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED)) {
finalintstate= intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE,
NfcAdapter.STATE_OFF);
switch (state) {
case NfcAdapter.STATE_OFF:
Log.d("NFCADAPTER", "Adapter Off");
break;
case NfcAdapter.STATE_TURNING_OFF:
Log.d("NFCADAPTER", "Adapter Turning Off");
break;
case NfcAdapter.STATE_TURNING_ON:
Log.d("NFCADAPTER", "Adapter Turning On");
break;
case NfcAdapter.STATE_ON:
Log.d("NFCADAPTER", "Adapter On");
setupNfcAdapter();
break;
}
}
}
};
Solution 2:
I found a solution (well, more a workaround) that works for my situation.
I think what happens is that the NfcService
is not aware that the activity is running in the foreground. The NfcService
keeps track of the foreground activity through a ForegroundUtils
which leverages an IProcessObserver
.
What I think is happening is that my activity sometimes becomes the foreground activity before this process observer is setup and therefore the NfcService
thinks my activity is not runnning in the foreground, preventing the call on the read method.
What I did as a workaround is to receive NfcAdapter.STATE_ON
changes by registering a receiver on NfcAdapter.ACTION_ADAPTER_STATE_CHANGED
in the activity. If this event is received this is considered a situation as described above and I kill and restart the app (see [1]). This is now observed by the ForgroundUtils
and I'm able to get into reader mode.
Post a Comment for "Nfcadpater.enablereadermode(...) Doesn't Work Consistently If Booting In Kiosk Mode Activity"