Android: Cambiar la configuración de NFC (on/off) mediante programación


Estoy tratando de cambiar la configuración de NFC (on/off) mediante programación en Android 2.3.3.

En el teléfono, bajo la "Configuración inalámbrica y de red",
puede elegir si desea usar NFC para leer e intercambiar etiquetas o no.

Así que me gustaría cambiar esta configuración en mi aplicación.
Pero no puedo encontrar una api para esto.

Estoy buscando algún código que probablemente se vería así:

WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled( on/off );
Author: OMG Ponies, 2011-05-10

5 answers

No puedes girarlo on/off manualmente pero puedes enviar al usuario a las preferencias si es off:

    if (!nfcForegroundUtil.getNfc().isEnabled())
    {
        Toast.makeText(getApplicationContext(), "Please activate NFC and press Back to return to the application!", Toast.LENGTH_LONG).show();
        startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
    }

El método {[3] } solo devuelve el nfcadapter:

Nfc = NfcAdapter.getDefaultAdapter (actividad.getApplicationContext());

 29
Author: Sven Haiges,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-21 12:55:39

No es posible programáticamente sin dispositivo de enraizamiento. Pero puede iniciar NFC Settings Activity por intent action Settings.ACTION_NFC_SETTINGS para el nivel de api 16 y superior. Para api Settings.ACTION_WIRELESS_SETTINGS

La respuesta seleccionada anterior sugiere usar WIFI_SETTINGS pero podemos movernos directamente a NFC_SETTINGS

Aquí está el ejemplo:

android.nfc.NfcAdapter mNfcAdapter= android.nfc.NfcAdapter.getDefaultAdapter(v.getContext());

            if (!mNfcAdapter.isEnabled()) {

                AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getContext());
                alertbox.setTitle("Info");
                alertbox.setMessage(getString(R.string.msg_nfcon));
                alertbox.setPositiveButton("Turn On", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                            startActivity(intent);
                        }
                    }
                });
                alertbox.setNegativeButton("Close", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                alertbox.show();

            }
 37
Author: Kishan Raval,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-21 13:25:43

Si quieres hacerlo programáticamente, apperently esta Q contiene la respuesta:

¿Cómo puedo habilitar NFC reader a través de API?

Editar

No contenía la respuesta, pero contenía la clave de la respuesta, en la que basé mi código con el que respondí en la Q.

Lo pegaré aquí también en caso de que alguien esté interesado.

Lo tengo trabajando a través de la reflexión

Este código funciona en API 15, no lo he comprobado con otras versiones yet

public boolean changeNfcEnabled(Context context, boolean enabled) {
    // Turn NFC on/off
    final boolean desiredState = enabled;
    mNfcAdapter = NfcAdapter.getDefaultAdapter(context);

    if (mNfcAdapter == null) {
        // NFC is not supported
        return false;
    }

    new Thread("toggleNFC") {
        public void run() {
            Log.d(TAG, "Setting NFC enabled state to: " + desiredState);
            boolean success = false;
            Class<?> NfcManagerClass;
            Method setNfcEnabled, setNfcDisabled;
            boolean Nfc;
            if (desiredState) {
                try {
                    NfcManagerClass = Class.forName(mNfcAdapter.getClass().getName());
                    setNfcEnabled   = NfcManagerClass.getDeclaredMethod("enable");
                    setNfcEnabled.setAccessible(true);
                    Nfc             = (Boolean) setNfcEnabled.invoke(mNfcAdapter);
                    success         = Nfc;
                } catch (ClassNotFoundException e) {
                } catch (NoSuchMethodException e) {
                } catch (IllegalArgumentException e) {
                } catch (IllegalAccessException e) {
                } catch (InvocationTargetException e) {
                }
            } else {
                try {
                    NfcManagerClass = Class.forName(mNfcAdapter.getClass().getName());
                    setNfcDisabled  = NfcManagerClass.getDeclaredMethod("disable");
                    setNfcDisabled.setAccessible(true);
                    Nfc             = (Boolean) setNfcDisabled.invoke(mNfcAdapter);
                    success         = Nfc;
                } catch (ClassNotFoundException e) {
                } catch (NoSuchMethodException e) {
                } catch (IllegalArgumentException e) {
                } catch (IllegalAccessException e) {
                } catch (InvocationTargetException e) {
                }
            }
            if (success) {
                Log.d(TAG, "Successfully changed NFC enabled state to "+ desiredState);
            } else {
                Log.w(TAG, "Error setting NFC enabled state to "+ desiredState);
            }
        }
    }.start();
    return false;
}//end method

Sin embargo, esto requiere 2 permisos, póngalos en el manifiesto:

 <!-- change NFC status toggle -->
    <uses-permission android:name="android.permission.NFC" />
    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />

El estado del botón NFC cambia en consecuencia cuando se utiliza el código, por lo que no hay problemas al hacerlo manualmente en el menú seetings.


Para aclarar: Este código no funciona en dispositivos normales. Hay formas de evitarlo, pero al menos requiere root.

 8
Author: slinden77,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:56

Puedes controlar las transferencias NFC y esas cosas. Pero por ahora encenderlo y apagarlo no es posible: (

 0
Author: Rejinderi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-10 04:27:03

Por favor, compruebe esta URL a continuación todo se da paso a paso.

Http://ranjithdroid.blogspot.com/2015/11/turn-onoff-android-nfc-by.html

 0
Author: Ranjith Subramaniam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-04 08:15:28