How to check whether NFC is enabled or not in android?

后端 未结 5 1192
走了就别回头了
走了就别回头了 2020-12-25 12:09

How can i check whether NFC is enabled or not programmatically? Is there any way to enable the NFC on the device from my program? Please help me

相关标签:
5条回答
  • 2020-12-25 12:43
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getApplicationContext());
        try {
            if (mNfcAdapter != null) {
                result = true;
            }
        }
    

    We can verify using NfcAdapter with context.

    0 讨论(0)
  • 2020-12-25 13:01

    I might be a little late here, but I've implemented a 'complete' example with detection of

    1. NFC capability (hardware), and
    2. Initial NFC state (enabled or disabled in settings), and
    3. Changes to the state

    I've also added a corresponding Beam example which uses the

    nfcAdapter.isNdefPushEnabled()
    

    method introduced in later Android versions to detect beam state like in 2) and 3).

    0 讨论(0)
  • 2020-12-25 13:04

    Use PackageManager and hasSystemFeature("android.hardware.nfc"), matching the <uses-feature android:name="android.hardware.nfc" android:required="false" /> element you should have in your manifest.

    Since 2.3.3 you can also use NfcAdapter.getDefaultAdapter() to get the adapter (if available) and call its isEnabled() method to check whether NFC is currently turned on.

    0 讨论(0)
  • 2020-12-25 13:07

    This can be done simply using the following code:

    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    
    if (nfcAdapter == null) {
        // NFC is not available for device
    } else if (!nfcAdapter.isEnabled()) {
        // NFC is available for device but not enabled
    } else {
        // NFC is enabled
    }
    

    Remember that the user can turn off NFC, even while using your app.

    Source: https://developer.android.com/guide/topics/connectivity/nfc/nfc#manifest

    Although you can't programically enable NFC yourself, you can ask the user to enable it by having a button to open NFC settings like so:

    Intent intent
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        intent = new Intent(Settings.ACTION_NFC_SETTINGS);
    } else {
        Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
    }
    
    startActivity(intent);
    
    0 讨论(0)
  • 2020-12-25 13:08
    NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
    NfcAdapter adapter = manager.getDefaultAdapter();
    if (adapter != null && adapter.isEnabled()) {
        // adapter exists and is enabled.
    }
    

    You cannot enable the NFC programmatically. The user has to do it manually through settings or hardware button.

    0 讨论(0)
提交回复
热议问题