Android - Listening to NFC Adapter State Changed

微笑、不失礼 提交于 2019-12-01 18:44:36
ahmad

Thought I should post the answer for other people looking for the same problem, since I wasn't able to find one easily.

Add the following code to your activities onCreate() method:

IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
this.registerReceiver(mReceiver, filter);

Inner private class declared within your activity (or anywhere else you like):

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

        if (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:
                break;
            case NfcAdapter.STATE_TURNING_OFF:
                break;
            case NfcAdapter.STATE_ON:
                break;
            case NfcAdapter.STATE_TURNING_ON:
                break;
            }
        }
    }
};

@Override
public void onDestroy() {
    super.onDestroy();

    // Remove the broadcast listener
    this.unregisterReceiver(mReceiver);
}

  // The following check needs to also be added to the onResume
@Override
protected void onResume() 
    super.onResume();
    // Check for available NFC Adapter
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);

    if(adapter != null && adapter.isEnabled()) {
        createNfcDetector();
        //NFC is available on device, but disabled
    }
    else {
        //NFC Is available and enabled
    }
}

You can use ACTION_ADAPTER_STATE_CHANGED to receive a broadcast message when the state of the adapter changes, but that option is only available in API 18 and above. See this for the documentation.

For prior to 18, I don't know of a way to do this unfortunately.

Also, as an aside, the android.provider.Settings.ACTION_NFC_SETTINGS will work on API levels 16 and above. For prior versions, the NFC settings are under "wireless settings". Take a look at the ensureSensorIsOn method at the bottom of this blog post for a code sample that checks against the API level and redirects to the correct settings pane.

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