Android: Changing NFC settings (on/off) programmatically
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 );
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();
}
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());