Programmatically turn ON/OFF NFC in Android

 Programmatically turn ON/OFF NFC in Android

I hope most of you know about NFC (Near Field Communication). It's an innovative version of RFID to read and write a small chunk of information by using the electromagnetic field.


In this post, I am going to explain how to turn ON/OFF NFC by using the android APIs.

Google has some restrictions on Nfc power on/off for developers. Obviously, we know it is a user feature to turn on/off by android system setting menu.

Follow the below steps:
  1. The device should be a rooted device or system application acceptable device.
  2. The developer needs to be accessed to handle power ON/OFF API by Java reflection.
  3. The application should have NFC permission as well as writing secure setting permission.
We need to specify all below permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<uses-feature android:name="android.hardware.nfc" android:required="false" />

Implementation for turn on/off a device

public static boolean powerNfc(boolean isOn, Context context) {
    boolean success = false;
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);

    if (nfcAdapter != null) {
        Class<?> NfcManagerClass;
        Method setNfcEnabled;
        try {
            NfcManagerClass = Class.forName(nfcAdapter.getClass().getName());
            setNfcEnabled = NfcManagerClass.getDeclaredMethod(isOn
                    ? "enable" : "disable");
            setNfcEnabled.setAccessible(true);
            success = (Boolean) setNfcEnabled.invoke(nfcAdapter);
        } catch (ClassNotFoundException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        } catch (NoSuchMethodException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        } catch (IllegalArgumentException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        } catch (IllegalAccessException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        } catch (InvocationTargetException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    return success;
}

Check the NFC power status by using below method.

This is a public method, so we don't need to access this by using any reflection techniques. So simply you could call the method from an adapter object.
public static boolean checkNfcPowerStatus(Context context) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
    boolean enabled = false;

    if (nfcAdapter != null) {
        enabled = nfcAdapter.isEnabled();
    }

    return enabled;
}
GitHub Download:https://github.com/RanjithSubraman/AndroidNfcPower


Comments

  1. Hi Ranjith, Thanks for the code. But getting an exception "InvocationTargetException" when enabling the NFC through code.

    ReplyDelete
    Replies
    1. Great....Before executing this code. Please confirm you are running this code in a rooted android device. or using this application as a system application.

      Delete
  2. It do not work for me also, my smart phone as Nexus S Android 4.1.1 .
    rooted and 2 permission , and 1 feature


    It throws the InvocationTargetException

    ReplyDelete
    Replies
    1. I think, problem was occurred by the version of Android. Pleaser have look on this URL, because it was mentioned by Android team.

      https://code.google.com/p/android/issues/detail?id=24466

      Delete
    2. It will be working only with Rooted or system application acceptable devices because it requires WRITE_SECURE_SETTINGS permission to access low lever firmware commands which i have defined inside AndroidManifest.xml. If your device isn't rooted, you will be getting an exception in Android studio console.

      Delete
  3. it is better to provide complete application,some more extra information

    ReplyDelete
    Replies
    1. Hi Naroju, The complete application was provided by github url on bottom of the application.

      Delete
  4. Hey Rajnith,
    it's clear that you have used reflection to get this working. Can you please help me with how do you know that the code will only work on rooted device? What are the bread crumbs that tells you about the rooted nature of the code.

    ReplyDelete
    Replies
    1. Thank you, it's really good question.

      It will be working only with Rooted or system application acceptable devices because it requires WRITE_SECURE_SETTINGS permission to access low lever firmware commands which i have defined inside AndroidManifest.xml. If your device isn't rooted, you will be getting an exception in Android studio console.

      Exception: java.lang.SecurityException: WRITE_SECURE_SETTINGS permission

      Delete
  5. Hi Ranjith, thanks for this absolute interesting topic. I search for my rooted android phone (which runs CM11) a way to enforce the NFC function. Unfortunately I must ask here now some stupid questions. First, exist there a way to run a comparable code in the terminal? (The command "service call nfc 5" doesn't help.) Exist there the possibility to build a script / batch file that enforce NFC on terminal? Thanks for any hints, Kind regards.

    ReplyDelete
    Replies
    1. Thank you for your question.

      It's really interesting question. I think, you are trying to handle Nfc with some short of commands because your device look like a robot some electronic device with NFC adapter. Obviously this code wouldn't help you directly to write some short of script or command because this is a pure java with android api code, but Android NDK may help you access this code by using C or C++, and also that could be early converted as command or script. Let me know if you figured it out.

      Delete
  6. hello, i just root samsung galaxy j5 2016 but NFC not turn on after i click toggle of in your application, what happen ?thx

    ReplyDelete
  7. what if we get mNfcadapter as null??

    ReplyDelete
    Replies
    1. Look like your device doesn't have NFC unit. In case if it has a NFC unit, you need to verify manually first by using setting menu. If that success go-ahead with programming.

      Delete
    2. I did the manual one.but after rebooting the device i am getiing the adapter as null.

      Delete
    3. I don't know what you are meaning "after rebooting the device". Were you able to get read/write the NFC by using setting on/off mechanism? In addition, NFC won't work on emulators. Please put some debug point.

      Delete

Post a Comment

Popular posts from this blog

Sign-on by using Google OAuth2

Setup to execute Apache Spark in Cloudera