Android:以编程方式更改 NFC 设置(开/关)

发布于 2024-11-06 02:26:45 字数 310 浏览 0 评论 0原文

我尝试在 Android 2.3.3 上以编程方式更改 NFC 设置(开/关)。

在手机上的“无线和网络设置”下,
您可以选择是否使用NFC来读取和交换标签。

所以我想在我的应用程序中切换此设置。
但我似乎找不到这方面的 api。

我正在寻找一些可能如下所示的代码:

WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled( on/off );

I trying to change NFC settings (on/off) programmatically on Android 2.3.3.

On the phone, under the "Wireless & network settings",
you can choose to set whether you want to use NFC to read and exchange tags or not.

So I would like to toggle this setting in my application.
But I can't seem to find an api for this.

I'm looking for some code that would probably look like this:

WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled( on/off );

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

把时间冻结 2024-11-13 02:26:45

如果没有生根设备,则无法以编程方式实现。
但您可以通过 API 级别 16 及更高版本的意图操作 Settings.ACTION_NFC_SETTINGS 启动 NFC 设置活动。对于 API < 16 使用 Settings.ACTION_WIRELESS_SETTINGS

之前选择的答案建议使用 WIFI_SETTINGS 但我们可以直接转到 NFC_SETTINGS

下面是示例:

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();

            }

It's not possible programatically without rooting device.
But you can start NFC Settings Activity by intent action Settings.ACTION_NFC_SETTINGS for api level 16 and above. For api < 16 use Settings.ACTION_WIRELESS_SETTINGS

Previous selected answer suggests to use WIFI_SETTINGS but we can directly move to NFC_SETTINGS

Here's the example :

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();

            }
情何以堪。 2024-11-13 02:26:45

您无法手动打开/关闭,但如果它关闭,您可以将用户发送到首选项:

    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));
    }

方法 getNfc() 仅返回nfcadapter

nfc = NfcAdapter.getDefaultAdapter(activity.getApplicationContext());

You can not turn it on/off manually but you can send the user to the preferences if it is 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));
    }

Method getNfc() just returns the nfcadapter:

nfc = NfcAdapter.getDefaultAdapter(activity.getApplicationContext());

温柔一刀 2024-11-13 02:26:45

如果您想以编程方式执行此操作,显然这个问题包含答案:

如何我可以通过 API 启用 NFC 阅读器吗?

编辑

它没有给出答案,但它掌握了答案的关键,我在 Q 中回答的代码就是基于它的。

如果有人感兴趣,我也会将其粘贴在这里。

我通过反射得到了它工作

此代码适用于 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

需要 2 个权限,请将它们放入清单中:

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

使用代码时,NFC 按钮的状态会相应切换,因此没有在设置菜单中手动执行此操作时出现问题。


澄清此代码不适用于普通设备。有很多方法,但至少需要 root

if you want to do it programmatically, apperently this Q holds the answer:

How can I enable NFC reader via API?

Edit

it didn't hold the answer, but it held the key to the answer, on which I based my code I answered with in the Q.

I will paste it here as well in case anyone's interested.

I got it working through reflection

This code works on API 15, haven't checked it against other verions 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

This requires 2 permissions though, put them in the manifest:

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

The NFC button's state switches accordingly when the code is used, so there are no issues when doing it manually in the seetings menu.


To clarify: This code doesn't work on normal devices. There are ways around, but at least it requires root.

朕就是辣么酷 2024-11-13 02:26:45

您可以控制 NFC 传输等。但目前无法打开和关闭它:(

You can control the NFC transfers and stuff. But for now turning it on and off is not possible :(

倾城月光淡如水﹏ 2024-11-13 02:26:45

请检查下面的 URL,所有内容均按步骤给出。

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

Please check this below URL everything is given as step by step.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文