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

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;
}
主站蜘蛛池模板: 青阳县| 五常市| 永州市| 黔东| 西和县| 蒲城县| 泸溪县| 宜兴市| 沅江市| 广宗县| 德庆县| 临西县| 鲁山县| 准格尔旗| 伊宁县| 鹤壁市| 始兴县| 呼和浩特市| 康保县| 西宁市| 河间市| 云安县| 旬邑县| 东阿县| 邵阳市| 射洪县| 卢龙县| 开鲁县| 东台市| 贡山| 河北区| 鄂伦春自治旗| 黔江区| 衡山县| 建始县| 桦川县| 平遥县| 门源| 茌平县| 宁都县| 衢州市|