1

我正在实现一个使用 NFC 芯片的应用程序。当手机设置为飞行模式时,NFC 将关闭,可以通过首选项手动打开。我想以编程方式打开它,这样我就可以继续使用 NFC 芯片来达到我的目的。

我发现这似乎不适用于我的银河系 (API 14)。作者提到他只在 API 15 上测试过。

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

https://stackoverflow.com/a/11286431/1018288

我总是得到 Log.w(TAG, "Error setting NFC enabled state to "+ desiredState); 执行时的消息。有任何想法吗?

4

0 回答 0