Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I enable NFC reader via API?

Tags:

android

nfc

There is any way I can enable Android NFC reader using API?

like image 994
GetUsername Avatar asked Jun 28 '11 15:06

GetUsername


1 Answers

So apparently there is no way to enable the NFC from the API, even though Google does so within their source code (see below).

If you look at a line from the API for NfcAdapter.isEnabled():

Return true if this NFC Adapter has any features enabled.

Application may use this as a helper to suggest that the user should turn on NFC in Settings.

If this method returns false, the NFC hardware is guaranteed not to generate or respond to any NFC transactions.

It looks like there is no way to do it within the API. Bummer. Your best bet is a dialog to inform the user they need to enable it in the settings, and perhaps launch a settings intent.

EDIT: The following is from the source, but it looks like they didn't allow the user to implement the methods in the API (I'm confused about this).

I found this from the android source code to help enable and disable the adapter.

Relevant source:

public boolean onPreferenceChange(Preference preference,
        Object value) {
    // Turn NFC on/off

    final boolean desiredState = (Boolean) value;
    mCheckbox.setEnabled(false);

    // Start async update of the NFC adapter state, as the API is
    // unfortunately blocking...
    new Thread("toggleNFC") {
        public void run() {
            Log.d(TAG, "Setting NFC enabled state to: "
                    + desiredState);
            boolean success = false;
            if (desiredState) {
                success = mNfcAdapter.enable();
            } else {
                success = mNfcAdapter.disable();
            }
            if (success) {
                Log.d(TAG,
                        "Successfully changed NFC enabled state to "
                                + desiredState);
                mHandler.post(new Runnable() {
                    public void run() {
                        handleNfcStateChanged(desiredState);
                    }
                });
            } else {
                Log.w(TAG, "Error setting NFC enabled state to "
                        + desiredState);
                mHandler.post(new Runnable() {
                    public void run() {
                        mCheckbox.setEnabled(true);
                        mCheckbox
                                .setSummary(R.string.nfc_toggle_error);
                    }
                });
            }
        }
    }.start();
    return false;
}
like image 104
John Leehey Avatar answered Sep 18 '22 17:09

John Leehey