我该如何在程序中检查NFC功能是否已启用?有没有办法从我的程序中启用设备上的NFC?请帮帮我。
NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
// adapter exists and is enabled.
}
你无法通过编程方式启用NFC。用户必须手动通过设置或硬件按钮启用它。
您可以简单地使用以下代码来完成:
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
// NFC is not available for device
} else if (!nfcAdapter.isEnabled()) {
// NFC is available for device but not enabled
} else {
// NFC is enabled
}
请记住,用户可以在使用您的应用时关闭NFC。
来源:https://developer.android.com/guide/topics/connectivity/nfc/nfc#manifest
尽管您无法以编程方式自行启用NFC,但可以通过添加一个按钮来打开NFC设置并要求用户启用它:
Intent intent
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
intent = new Intent(Settings.ACTION_NFC_SETTINGS);
} else {
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
}
startActivity(intent);
使用PackageManager
和hasSystemFeature("android.hardware.nfc")
,匹配您在清单文件中应该有的<uses-feature android:name="android.hardware.nfc" android:required="false" />
元素。
自2.3.3以来,您还可以使用NfcAdapter.getDefaultAdapter()
获取适配器(如果可用),并调用其isEnabled()
方法检查NFC当前是否已打开。
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getApplicationContext());
try {
if (mNfcAdapter != null) {
result = true;
}
}