How to check whether NFC is enabled or not in android?

后端 未结 5 1233
走了就别回头了
走了就别回头了 2020-12-25 12:09

How can i check whether NFC is enabled or not programmatically? Is there any way to enable the NFC on the device from my program? Please help me

5条回答
  •  误落风尘
    2020-12-25 13:07

    This can be done simply using the following code:

    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
    }
    

    Remember that the user can turn off NFC, even while using your app.

    Source: https://developer.android.com/guide/topics/connectivity/nfc/nfc#manifest

    Although you can't programically enable NFC yourself, you can ask the user to enable it by having a button to open NFC settings like so:

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

提交回复
热议问题