36

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

THelper
  • 15,333
  • 6
  • 64
  • 104
Santhosh
  • 4,956
  • 12
  • 62
  • 90

5 Answers5

66
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.

Ron
  • 24,175
  • 8
  • 56
  • 97
  • so if the returned value is FALSE, it means the device doesnt have the NFC capability, is that true @userSeven7s? – gumuruh Jul 05 '14 at 07:43
  • 1
    That is not correct. If the adapter is null, the device does not have NFC. Explanation on the [Developer website](http://developer.android.com/guide/topics/connectivity/nfc/nfc.html#manifest) – Marko Nov 26 '14 at 14:02
15

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);
Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231
9

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).

ThomasRS
  • 8,215
  • 5
  • 33
  • 48
8

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.

Praful Bhatnagar
  • 7,425
  • 2
  • 36
  • 44
Ahsan
  • 2,964
  • 11
  • 53
  • 96
0
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getApplicationContext());
    try {
        if (mNfcAdapter != null) {
            result = true;
        }
    }

We can verify using NfcAdapter with context.