Return the NfcAdapter object or null. - Android Hardware

Android examples for Hardware:NFC

Description

Return the NfcAdapter object or null.

Demo Code

/**/* w  w w .  j av  a 2s.  c o  m*/
 * Copyright 2014 Bastian Treger
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.* You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * 
 * 
 * With the help of AndroidNfcHepler you can check current Near field communication (NFC) state.
 * In detail you can check:
 * 
 * - if the device is Near Field Communication capable / has NFC hardware
 * - if NFC is enabled 
 * - if Android Beam (p2p protocol) is enabled
 * 
 * NFC is badly supported since Android 2.3.0 (API 9). The APIs was improved in Android 2.3.3 (API 10).
 * Therefore AndroidNfcHepler infers at least API 10 for proper NFC usage.
 * 
 * @author btreger
 */
//package com.java2s;

import android.annotation.SuppressLint;
import android.content.Context;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.os.Build;

public class Main {
    private static final int MIN_SDK_INT_FOR_NFC = Build.VERSION_CODES.GINGERBREAD_MR1;

    /**
     * Return the NfcAdapter object or null. All devices without a hardware NFC module
     * will return null. All devices with Android 2.3.0 (API 9) or lower will return null,
     * caused by missing API support. 
     * 
     * @param context Android Context
     * @return NfcAdapter object or null
     */
    @SuppressLint("NewApi")
    public static NfcAdapter getNfcAdapter(Context context) {
        if (Build.VERSION.SDK_INT < MIN_SDK_INT_FOR_NFC) {
            return null;
        } else {
            final NfcManager manager = (NfcManager) context
                    .getSystemService(Context.NFC_SERVICE);
            final NfcAdapter adapter = manager.getDefaultAdapter();
            return adapter;
        }
    }
}

Related Tutorials