1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.settings.nfc;
18 
19 import android.content.BroadcastReceiver;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 import android.nfc.NfcAdapter;
24 
25 /**
26  * BaseNfcEnabler is a abstract helper to manage the Nfc state for Nfc and Android Beam
27  * preference. It will receive intent and update state to ensure preference show correct state.
28  */
29 public abstract class BaseNfcEnabler {
30     protected final Context mContext;
31     protected final NfcAdapter mNfcAdapter;
32     private final IntentFilter mIntentFilter;
33 
34     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
35         @Override
36         public void onReceive(Context context, Intent intent) {
37             String action = intent.getAction();
38             if (NfcAdapter.ACTION_ADAPTER_STATE_CHANGED.equals(action)) {
39                 handleNfcStateChanged(intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE,
40                         NfcAdapter.STATE_OFF));
41             }
42         }
43     };
44 
BaseNfcEnabler(Context context)45     public BaseNfcEnabler(Context context) {
46         mContext = context;
47         mNfcAdapter = NfcAdapter.getDefaultAdapter(context);
48 
49         if (!isNfcAvailable()) {
50             // NFC is not supported
51             mIntentFilter = null;
52             return;
53         }
54         mIntentFilter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
55     }
56 
resume()57     public void resume() {
58         if (!isNfcAvailable()) {
59             return;
60         }
61         handleNfcStateChanged(mNfcAdapter.getAdapterState());
62         mContext.registerReceiver(mReceiver, mIntentFilter);
63     }
64 
pause()65     public void pause() {
66         if (!isNfcAvailable()) {
67             return;
68         }
69         mContext.unregisterReceiver(mReceiver);
70     }
71 
isNfcAvailable()72     public boolean isNfcAvailable() {
73         return mNfcAdapter != null;
74     }
75 
handleNfcStateChanged(int newState)76     protected abstract void handleNfcStateChanged(int newState);
77 }
78