- Near Field Communication with Android Cookbook
- Vitor Subtil
- 316字
- 2021-07-16 11:37:22
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:
- Open the previously created
NfcBookCh1Example1
project. - Open
MainActivity
located undernfcbook.ch1.example1
and place the following code inside theonCreate
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(); }
- 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; }
- 我們都是數據控:用大數據改變商業、生活和思維方式
- SQL Server 2008數據庫應用技術(第二版)
- 分布式數據庫系統:大數據時代新型數據庫技術(第3版)
- Python廣告數據挖掘與分析實戰
- 圖解機器學習算法
- WS-BPEL 2.0 Beginner's Guide
- 達夢數據庫性能優化
- Apache Kylin權威指南
- Construct 2 Game Development by Example
- INSTANT Android Fragmentation Management How-to
- 計算機組裝與維護(微課版)
- 大數據數學基礎(Python語言描述)
- Mastering ROS for Robotics Programming(Second Edition)
- Oracle 11g數據庫管理與開發基礎教程
- Access 2010數據庫應用技術教程(第二版)