NFCAdpater.enableReaderMode(…) doesn't work consistently if booting in Kiosk mode activity

南楼画角 提交于 2020-06-13 05:34:07

问题


I have an application which starts in Kiosk mode and should read and react on NFCTags. It's using enableReaderMode on the NFCAdapter in onResume to start reading them. Everything works fine if the app is e.g. (re-)started during development. However, if I reboot the device (and the activity gets started automatically) the activity is only sometimes put into the right mode, but often only plays the NFC system sound and my handleTag is not called.

From what I logged, the NFCAdapter setup code I have is correctly called in all circumstances

I tried enableForegroundDispatch as well, but there's the same effect. I also tried periodically recalling enableReaderMode but it also has the same effect.

Anybody has an idea what's going on?

Update

I see this error message in the logs when I try to set the reader mode in the cases where it fails

NfcService: setReaderMode: Caller is not in foreground and is not system process.

Although the activity is clearly visible in the forgreound.

Phone is a Google Pixel 3

The application is device owner through

adb shell dpm set-device-owner ...

The manifest of the application

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:testOnly="true">

    <!-- snip DeviceAdminReceiver -->

    <activity
        android:name=".FullscreenActivity"
        android:screenOrientation="reverseLandscape"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/app_name"
        android:theme="@style/FullscreenTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.HOME" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" />

The FullscreenActivity which should handle the NFC Tag

public class FullscreenActivity extends AppCompatActivity {
  NfcAdapter mAdapter;
  private DevicePolicyManager mDevicePolicyManager;
  private ComponentName mAdminComponentName;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mDevicePolicyManager = (DevicePolicyManager) getSystemService(
            Context.DEVICE_POLICY_SERVICE);
    if (mDevicePolicyManager.isDeviceOwnerApp(getPackageName())) {
        mAdminComponentName = MyDeviceAdminReceiver.getComponentName(this);

        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MAIN);
        intentFilter.addCategory(Intent.CATEGORY_HOME);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        mDevicePolicyManager.addPersistentPreferredActivity(
                mAdminComponentName, intentFilter,
                new ComponentName(getPackageName(),
                        FullscreenActivity.class.getName()));

        mDevicePolicyManager.setLockTaskPackages(mAdminComponentName,
                new String[]{getPackageName()});

        mDevicePolicyManager.setKeyguardDisabled(mAdminComponentName, true);

    }
    startLockTask();
  }

  @Override
  public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        setFullscreenFlags();
    }
  }

  private void setFullscreenFlags() {
    getWindow().getDecorView()
            .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
  }

  @Override
  protected void onResume() {
    super.onResume();
    setFullscreenFlags();
    mAdapter = NfcAdapter.getDefaultAdapter(this);
    setupNfcAdapter();
  }

  private void setupNfcAdapter() {
    if (mAdapter == null) return;

    Bundle options = new Bundle();
    // No sure this is needed
    options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 50000);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass())
                    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    mAdapter.enableReaderMode(this, this::handleTag,
            NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS |
                    NfcAdapter.FLAG_READER_NFC_A |
                    NfcAdapter.FLAG_READER_NFC_B |
                    NfcAdapter.FLAG_READER_NFC_F |
                    NfcAdapter.FLAG_READER_NFC_V, options);
  }

  @Override
  protected void onPause() {
    super.onPause();

    if (mAdapter != null) {
        mAdapter.disableReaderMode(this);
    }
  }

  private void handleTag(Tag tag) {
    Log.d("NFCADAPTER", "tag detected");
  }

}


回答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.

  1. Try checking NfcAdapter.isEnabled() is true to help determine if the NFC hardware is actually available before your try enableReaderMode

  2. Setup a broadcaster receiver to log the NFC service states and enableReaderMode when it is ready as well as in onResume.

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:-

protected void onCreate(Bundle savedInstanceState) {
  // All the normal onCreate Stuff

// Listen for changes NFC settings
        IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
        this.registerReceiver(mReceiver, filter);
}


private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action != null && action.equals(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED)) {
                final int state = 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;
                }
            }
        }
    };




回答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.

[1] How do I programmatically "restart" an Android app?



来源:https://stackoverflow.com/questions/61142449/nfcadpater-enablereadermode-doesnt-work-consistently-if-booting-in-kiosk-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!