官术网_书友最值得收藏!

Verifying whether the device has an NFC adapter

The very first lines of code we write in an app that uses NFC should be a simple validation that tests for the NFC adapter.

How to do it…

We'll create an application that shows a Toast saying whether the device has the NFC adapter, as follows:

  1. Open the previously created NfcBookCh1Example1 project.
  2. Open MainActivity located under nfcbook.ch1.example1 and place the following code inside the onCreate method:
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    
    if (nfcAdapter != null && nfcAdapter.isEnabled()) {
      Toast.makeText(this, "NFC is available.", Toast.LENGTH_LONG).show();
    } else {
      Toast.makeText(this, "NFC is not available on this device. This application may not work correctly.", 
    Toast.LENGTH_LONG).show();
    }
  3. Run the application and try enabling and disabling NFC and see the different results.

How it works…

Android provides a simple way to request the Adapter object by calling getDefaultAdapter([context]). If a valid NfcAdapter instance is returned, the NFC adapter is available; however, we still need to check if it is enabled by calling the isEnabled() method. Otherwise, we need to inform the user that the application may not function correctly as NFC is a required feature. Testing the result for a null value is the simplest way to know if NFC is available to us. However, we can also use the hasSystemFeature method from the PackageManager class to do this validation.

There's more…

Testing for NFC is an operation that we will probably do very often. So, we can create a simple method and call it every time we need to test for NFC, as shown in the following code:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  if (hasNfc()) {
    Toast.makeText(this, "NFC is available.", Toast.LENGTH_LONG).show();
  } else {
    Toast.makeText(this, "NFC is not available on this device. This application may not work correctly.", Toast.LENGTH_LONG).show();
  }
}

boolean hasNfc() {
  boolean hasFeature = getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC);
  boolean isEnabled = NfcAdapter.getDefaultAdapter(this).isEnabled();
  
  return hasFeature && isEnabled;
}
主站蜘蛛池模板: 来宾市| 格尔木市| 土默特右旗| 浮梁县| 旺苍县| 行唐县| 江津市| 夹江县| 新巴尔虎左旗| 浦县| 屏东市| 侯马市| 大冶市| 澄城县| 常宁市| 开封市| 那坡县| 文水县| 阿图什市| 襄汾县| 仙居县| 高淳县| 海林市| 平原县| 克什克腾旗| 吉木乃县| 甘孜县| 临安市| 巴中市| 温州市| 奎屯市| 金塔县| 疏附县| 鄯善县| 左贡县| 渭南市| 易门县| 富阳市| 长岛县| 和硕县| 托里县|