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

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;
}
主站蜘蛛池模板: 苍梧县| 法库县| 政和县| 肇源县| 张家口市| 阳原县| 新沂市| 湾仔区| 新民市| 凤翔县| 循化| 阜宁县| 牟定县| 盘山县| 聂荣县| 新干县| 合作市| 都昌县| 凤山市| 松原市| 霍林郭勒市| 弥渡县| 宝丰县| 安岳县| 大荔县| 延庆县| 色达县| 淳安县| 梨树县| 达尔| 开化县| 称多县| 民勤县| 梨树县| 承德市| 旺苍县| 长宁区| 建阳市| 台东市| 吉林省| 绿春县|