1 package org.average.nfcauthcr;
3 import android.app.Service;
4 import android.app.PendingIntent;
5 import android.content.Intent;
6 import android.content.IntentFilter;
7 import android.content.SharedPreferences;
8 import android.content.SharedPreferences.Editor;
9 import android.nfc.NfcAdapter;
10 import android.nfc.Tag;
11 import android.nfc.TagLostException;
12 import android.nfc.tech.IsoDep;
13 import android.os.Binder;
14 import android.os.IBinder;
15 import android.preference.PreferenceManager;
16 import android.util.Log;
17 import android.widget.Toast;
19 import org.average.nfcauthcr.CheckConnector;
20 import org.average.nfcauthcr.YkNeo;
21 import org.average.nfcauthcr.CRException;
23 public class Check extends Service {
25 private final String TAG = getClass().getName();
27 private final CheckConnector checkConnector = new CheckConnector();
28 private SharedPreferences prefs;
30 private PendingIntent tagIntent;
33 public void onCreate() {
34 Log.v(TAG, "Created");
35 prefs = PreferenceManager.getDefaultSharedPreferences(this);
39 public int onStartCommand (Intent intent, int flags, int startId) {
40 Log.v(TAG, "Starting service");
41 this.startId = startId;
42 int slot = prefs.getInt("slot_number", -1);
48 return START_NOT_STICKY;
52 public IBinder onBind(Intent intent) {
53 Log.v(TAG, "Binding");
54 checkConnector.setService(this);
55 return checkConnector;
59 public void onDestroy() {
60 Log.v(TAG, "Finished the run");
65 protected void onNewIntent(Intent intent) {
66 Log.v(TAG, "NFC Intent arrived");
67 int slot = intent.getIntExtra("slot", -1);
68 byte[] challenge = intent.getByteArrayExtra("challenge");
69 if (slot <= 0) return;
70 Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
71 if (tag == null) return;
72 IsoDep isoTag = IsoDep.get(tag);
74 byte[] response = YkNeo.doChallengeYubiKey(
75 isoTag, slot, challenge);
76 Intent data = getIntent();
77 data.putExtra("response", response);
78 setResult(RESULT_OK, data);
79 } catch (CRException e) {
80 Log.v(TAG, e.getMessage());
81 Toast.makeText(this, e.getMessage(),
82 Toast.LENGTH_LONG).show();
87 private void enableDispatch(int slot) {
88 Intent intent = getIntent();
89 intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
90 intent.putExtra("slot", slot);
91 tagIntent = PendingIntent.getActivity(this, 0, intent, 0);
93 new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
94 NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
95 if (adapter == null) {
96 Toast.makeText(this, R.string.no_nfc,
97 Toast.LENGTH_LONG).show();
100 if (! adapter.isEnabled()) {
101 Toast.makeText(this, R.string.nfc_disabled,
102 Toast.LENGTH_LONG).show();
105 adapter.enableForegroundDispatch(
106 this, tagIntent, new IntentFilter[] {iso},
107 new String[][] {new String[] {IsoDep.class.getName()}});
110 private void disableDispatch() {
111 if (tagIntent != null) {
115 NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
116 if (adapter != null) {
117 adapter.disableForegroundDispatch(this);