Example usage for android.nfc NfcAdapter getDefaultAdapter

List of usage examples for android.nfc NfcAdapter getDefaultAdapter

Introduction

In this page you can find the example usage for android.nfc NfcAdapter getDefaultAdapter.

Prototype

public static NfcAdapter getDefaultAdapter(Context context) 

Source Link

Document

Helper to get the default NFC Adapter.

Usage

From source file:net.lp.hivawareness.v4.HIVAwarenessActivity.java

/** Called when the activity is first created. */
@Override//w  w  w  .  j ava2  s .  c  o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);

    //Save ApplicationContext
    applicationContext = this.getApplicationContext();

    enableStrictMode();

    if (DEBUG && mStrictModeAvailable) {
        StrictModeWrapper.allowThreadDiskWrites();//disables temporarily, reenables below
    }

    if (!DEBUG) {
        //BugSense uncaught exceptions analytics.
        BugSenseHandler.setup(this, BUGSENSE_API_KEY);
    }

    //Enable analytics session. Should be first (at least before any Flurry calls).
    if (!HIVAwarenessActivity.DEBUG)
        FlurryAgent.onStartSession(this, HIVAwarenessActivity.FLURRY_API_KEY);

    if (mBackupManagerAvailable) {
        mBackupManagerWrapper = new BackupManagerWrapper(this);//TODO: should this be app context?
        Log.i(TAG, "BackupManager API available.");
    } else {
        Log.i(TAG, "BackupManager API not available.");
    }

    //Load the default preferences values. Should be done first at every entry into the app.
    PreferenceManager.setDefaultValues(HIVAwarenessActivity.getAppCtxt(), PREFS, MODE_PRIVATE,
            R.xml.preferences, false);
    HIVAwarenessActivity.dataChanged();

    //Obtain a connection to the preferences.
    SharedPreferences prefs = getSharedPreferences(PREFS, MODE_PRIVATE);

    mGender = Gender.valueOf(prefs.getString(PREFS_GENDER, "male"));

    String region = prefs.getString(PREFS_REGION, null);
    if (region == null) {
        mRegion = null;
    }
    caught = prefs.getInt(PREFS_INFECTED, -1);

    if (caught == -1) {
        calculateInitial(mRegion == null);
    } else {

    }

    // Check for available NFC Adapter
    mNfcAdapter = NfcAdapter.getDefaultAdapter(HIVAwarenessActivity.getAppCtxt());
    if (mNfcAdapter == null) {
        Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
        if (!DEBUG)
            finish();
    }
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    try {
        ndef.addDataType("application/net.lp.hivawareness.beam");
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    mIntentFiltersArray = new IntentFilter[] { ndef };
    mTechListsArray = new String[][] { new String[] { NfcF.class.getName() } };
}

From source file:io.atrac613.AbstractNfcTagFragment.java

@Override
public void onResume() {
    Log.d(TAG, "*** AbstractNfcFeliCaTagFragment go Resume");

    //foregrandDispathch
    Activity a = this.getActivity();
    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    IntentFilter tag = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    try {/*from   w w  w. ja  v a  2 s.  com*/
        ndef.addDataType("*/*");
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    IntentFilter[] filters = new IntentFilter[] { ndef, tag, tech };

    PendingIntent pendingIntent = PendingIntent.getActivity(a, 0,
            new Intent(a, a.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this.getActivity());

    adapter.enableForegroundDispatch(this.getActivity(), pendingIntent, filters, registerTechList(mTechList));

    super.onResume();
}

From source file:com.securekey.sdk.sample.ReadCardActivity.java

private void enableForegroundDispatch() {
    Log.i("SDKSample", "enable foreground dispatch");
    if (NfcAdapter.getDefaultAdapter(this) != null) {
        try {/*  ww  w.  j av  a  2s.  c  o m*/
            NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this,
                    PendingIntent.getActivity(this, 0,
                            new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0),
                    new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) }, new String[][] {
                            new String[] { NfcA.class.getName() }, new String[] { NfcB.class.getName() } });
        } catch (Exception e) {
            Log.i("SDKSample", "enableForegroundDispatch failed");
        }
    }
}

From source file:org.croudtrip.fragments.offer.MyTripDriverFragment.java

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    setHasOptionsMenu(true);/*from ww  w .j av  a 2 s.c  om*/

    nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
    NdefRecord ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], null);
    ndefMessage = new NdefMessage(new NdefRecord[] { ndefRecord });

    return inflater.inflate(R.layout.fragment_my_trip_driver, container, false);
}

From source file:nl.hnogames.domoticz.NFCSettingsActivity.java

@Override
protected void onPause() {
    super.onPause();
    // disabling foreground dispatch:
    if (mNfcAdapter == null)
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    mNfcAdapter.disableForegroundDispatch(this);
}

From source file:de.stadtrallye.rallyesoft.MainActivity.java

@TargetApi(14)
private void initNFC() {
    NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
    if (nfc != null) {
        nfc.setNdefPushMessageCallback(new NfcCallback(server), this);
    }//from   www.ja v  a 2  s. c o  m
}

From source file:com.meiste.greg.ptw.tab.Standings.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    mSetupNeeded = GAE.isAccountSetupNeeded(getActivity());
    mChanged = false;/*from  w  ww  . j  a  va 2 s .c  o m*/
    mAccountSetupTime = Util.getAccountSetupTime(getActivity());
    setRetainInstance(true);

    final IntentFilter filter = new IntentFilter(PTW.INTENT_ACTION_STANDINGS);
    getActivity().registerReceiver(mBroadcastReceiver, filter);

    if (mSetupNeeded)
        return Util.getAccountSetupView(getActivity(), inflater, container);
    else if (mFailedConnect) {
        mFailedConnect = false;
        final View v = inflater.inflate(R.layout.no_connection, container, false);

        final Button retry = (Button) v.findViewById(R.id.retry);
        retry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                mChanged = true;
                notifyChanged();
            }
        });

        return v;
    } else if (!isStandingsPresent() || mConnecting) {
        if (!mConnecting) {
            mConnecting = true;
            GAE.getInstance(getActivity()).getPage(this, "standings");
        }
        return inflater.inflate(R.layout.connecting, container, false);
    }

    final View v = inflater.inflate(R.layout.list, container, false);
    mSwipeRefreshWidget = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_widget);
    mSwipeRefreshWidget.setOnRefreshListener(this);
    mSwipeRefreshWidget.setColorSchemeResources(R.color.refresh1, R.color.refresh2, R.color.refresh3,
            R.color.refresh4);

    final ListView lv = (ListView) v.findViewById(R.id.content);
    final View header = inflater.inflate(R.layout.standings_header, lv, false);
    mAdapter = new PlayerAdapter(getActivity());
    mAfterRace = (TextView) header.findViewById(R.id.after);
    mAfterRace.setText(getRaceAfterText(getActivity()));
    lv.addHeaderView(header, null, false);
    final View footer = inflater.inflate(R.layout.standings_footer, lv, false);
    mFooter = (TextView) footer.findViewById(R.id.standings_footer);
    mFooter.setText(getFooterText(getActivity()));
    lv.addFooterView(footer, null, false);
    lv.setAdapter(mAdapter);

    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, final View v, final int pos, final long id) {
            final Player player = (Player) parent.getItemAtPosition(pos);
            if (mAdapter.isSelf(player)) {
                Util.log("Opening privacy dialog");
                if (mPrivacyDialog == null) {
                    mPrivacyDialog = new PrivacyDialog(getActivity(), Standings.this);
                }
                mPrivacyDialog.show(mAdapter.getPlayerName());
            } else {
                Util.log("Opening friend action dialog");
                if (mFriendActionDialog == null) {
                    mFriendActionDialog = new FriendActionDialog(getActivity(), Standings.this);
                }
                mFriendActionDialog.show(player);
            }
        }
    });

    final ImageView iv = (ImageView) v.findViewById(R.id.add_friend);
    iv.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if ((NfcAdapter.getDefaultAdapter(getActivity()) != null)
                    && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
                    && mAdapter.getPlayer().isIdentifiable() && Gcm.isRegistered(getActivity())) {
                Util.log("NFC available. Need to ask user add method.");
                if (mFriendMethodDialog == null) {
                    mFriendMethodDialog = new FriendMethodDialog(getActivity(), Standings.this);
                }
                mFriendMethodDialog.reset();
                mFriendMethodDialog.show();
            } else {
                Util.log("NFC not available. Adding friend via username.");
                showFriendPlayerDialog();
            }
        }
    });

    if (mCheckName) {
        if ((mPrivacyDialog.getNewName() != null)
                && !mPrivacyDialog.getNewName().equals(mAdapter.getPlayerName())) {
            Toast.makeText(getActivity(), R.string.name_taken, Toast.LENGTH_SHORT).show();
        }
        mCheckName = false;
    }

    return v;
}

From source file:com.googlecode.android_scripting.facade.ui.NFCBeamTask.java

@SuppressLint("NewApi")
public boolean initNFCBeam() {
    Log.d(TAG, "initNFCBeam");
    mhandler = new Handler() {
        @Override/*from w w  w  .j  av  a  2s.co  m*/
        public void handleMessage(Message msg) {
            //Toast.makeText(getActivity().getApplicationContext(), "Master has sent content", Toast.LENGTH_SHORT).show();

            setResult("master", "ok");
        }
    };

    WBase = new _WBase(getActivity().getApplicationContext(), getActivity());
    dialogIndex = 1;

    _nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity().getApplicationContext());

    if (_nfcAdapter == null) {
        Toast.makeText(getActivity().getApplicationContext(),
                "NFC is not available, please upgrade your mobile", Toast.LENGTH_SHORT).show();

        /*WBase.setTxtDialogParam(R.drawable.alert_dialog_icon,
          "NFC is not available, please update your mobile",
          new OnClickListener() {
             @Override
             public void onClick(DialogInterface arg0, int arg1) {
             }
        });
        getActivity().showDialog(_WBase.DIALOG_NOTIFY_MESSAGE + dialogIndex);
        dialogIndex++;*/
    } else {

        if (!_nfcAdapter.isEnabled()) {
            Toast.makeText(getActivity().getApplicationContext(), "NFC is closed, please enable it with beam",
                    Toast.LENGTH_SHORT).show();

            /*            WBase.setTxtDialogParam(R.drawable.alert_dialog_icon,
                              "NFC is closed, please enable it with beam",
                              new OnClickListener() {
             @Override
             public void onClick(DialogInterface arg0, int arg1) {
                getActivity().startActivity(new Intent(
                      Settings.ACTION_NFC_SETTINGS));
             }
                              });
                        getActivity().showDialog(_WBase.DIALOG_NOTIFY_MESSAGE + dialogIndex);
                        dialogIndex++;*/
        } else {
            launchNFC();
            return true;
        }
    }
    return false;
}

From source file:com.sftoolworks.nfcoptions.SelectActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select);

    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    Intent intent = getIntent();/*from  w  ww .j  a  v a2  s  .  co  m*/
    Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

    String title = getString(R.string.default_select_title);

    TextView textViewBottom = (TextView) findViewById(R.id.textView2);
    textViewBottom.setText("");

    if (rawMessages != null) {

        ArrayList<Object> entries = new ArrayList<Object>();

        String data = null;

        for (Parcelable rawMessage : rawMessages) {
            NdefMessage message = (NdefMessage) rawMessage;
            NdefRecord[] records = message.getRecords();
            if (records.length > 1) {
                byte[] bArray = records[1].getPayload();
                byte languageLength = bArray[0];

                languageLength++; // because of the length byte

                data = new String(bArray, languageLength, bArray.length - languageLength);
            }
        }

        try {
            JSONObject json = (JSONObject) new JSONTokener(data).nextValue();
            if (json.has("title"))
                title = json.getString("title");
            if (json.has("key"))
                selectKey = json.getString("key");
            if (json.has("options")) {
                JSONArray arr = json.getJSONArray("options");
                for (int i = 0; i < arr.length(); i++) {
                    entries.add(parseJObject(arr.getJSONObject(i)));
                }
            }

            ListView list = (ListView) findViewById(R.id.listView1);
            list.setAdapter(new OptionListAdapter(this, entries.toArray()));

            list.setOnItemClickListener(new ListView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int index, long id) {
                    CheckBox cb = (CheckBox) view.findViewById(R.id.optionListCheckBox);
                    cb.setChecked(!cb.isChecked());
                }
            });

            textViewBottom.setText(getString(R.string.tap_again));

        } catch (Exception e) {
            String message = getString(R.string.json_err);
            message += "\n";
            message += e.getMessage();

            Toast.makeText(this, message, Toast.LENGTH_LONG).show();

            Log.d(TAG, getString(R.string.json_err));
            Log.d(TAG, e.toString());
            Log.d(TAG, data);
        }
    } else {
        title = getString(R.string.no_tag);
    }

    TextView msg = (TextView) findViewById(R.id.textView1);
    msg.setText(title);

}

From source file:net.eledge.android.europeana.gui.activity.RecordActivity.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void createNdefPushMessageCallback() {
    NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mNfcAdapter != null) {
        mNfcAdapter.setNdefPushMessageCallback(new CreateNdefMessageCallback() {
            @Override/*  w w  w .  j  a  va  2  s . c  o  m*/
            public NdefMessage createNdefMessage(NfcEvent event) {
                return new NdefMessage(new NdefRecord[] {
                        new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                                "application/vnd.net.eledge.android.europeana.record".getBytes(), new byte[0],
                                recordController.getPortalUrl().getBytes()),
                        NdefRecord.createApplicationRecord(getPackageName()) });
            }
        }, this);
    }
}