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:com.idevity.card.read.ReadMain.java

/**
 * Method onCreate./*from  w ww  .java 2 s  .co  m*/
 * 
 * @param savedInstanceState
 *            Bundle
 */
@TargetApi(19)
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read_main);

    /*
     * We will take over the NFC Interface while in the foreground so there
     * is no additional read attempt.
     * 
     * If on KitKat, we will set a filter and ignore any callbacks.
     */
    /****************** Initialize NFC ******************/
    if (debug) {
        Log.d(TAG, "Getting Adaptor...");
    }
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
    /*
     * Platform version specific handling: KitKat
     */
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
        if (debug) {
            Log.d(TAG, "Setting Adaptor up for KitKat");
        }
        ReaderCallback listener = new ReaderCallback() {
            public void onTagDiscovered(Tag tag) {
                /*
                 * Discard the tags here
                 */
                tag = null;
            }
        };
        int flags = NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
                | NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS;
        adapter.enableReaderMode(this, listener, flags, null);
    }

    // Get preferences / settings that have been saved
    // get the show log

    this.sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean showLog = this.sharedPref.getBoolean(g.getShowLog(), false);

    // Create the adapter that will return a fragment for each of the three
    // primary sections
    // of the app.
    mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager(), this.sharedPref);

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();

    // Specify that the Home/Up button should not be enabled, since there is
    // no hierarchical
    // parent.
    actionBar.setHomeButtonEnabled(true);

    // Specify that we will be displaying tabs in the action bar.
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Set up the ViewPager, attaching the adapter and setting up a listener
    // for when the
    // user swipes between sections.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            // When swiping between different app sections, select
            // the corresponding tab.
            // We can also use ActionBar.Tab#select() to do this if
            // we have a reference to the
            // Tab.
            actionBar.setSelectedNavigationItem(position);
        }
    });

    /*
     * Use the following to determine content to show in the tabs. First,
     * check to see if there is an active intent Also, check to see if there
     * is an active saved instance state If, active intent - use active
     * intent; if active intent = null, and saved instance state !null, use
     * saved instance state; else return user to "main" instructions
     */
    boolean hasIntent = false;
    boolean hasSavedData = false;

    try {
        if (getIntent().getExtras().getByteArray(g.getCardData()) != null) {
            hasIntent = true;
        }
    } catch (Throwable e) {
        Log.e(TAG, "Error: intent " + e.getMessage());
    }

    try {
        if (g.getCard() != null) {
            hasSavedData = true;
        }
    } catch (Throwable e) {
        Log.e(TAG, "Error: saved instance state " + e.getMessage());
    }

    // if intent, populate the variables with the intent values
    // else if saved instance, populate the same variables with the saved
    // instance state
    // else return user to read800-73 activity to read a new card

    if (hasIntent) {
        logStringBuffer = getIntent().getExtras().getString(g.getReaderLog());
        byte[] _data = getIntent().getExtras().getByteArray(g.getCardData());
        this.carddata = new CardData80073(_data);
        if (debug) {
            Log.d(TAG, "Using new card data");
        }
        g.putCard(carddata.toByteArray());
        g.putLogData(logStringBuffer);

    } else if (hasSavedData) {
        logStringBuffer = g.getLogData();
        byte[] _data = g.getCard();
        this.carddata = new CardData80073(_data);
        Log.e(TAG, "Using saved card data");
    } else {
        Intent returnuser = new Intent(this, Read80073.class);
        startActivity(returnuser);
        Log.e(TAG, "No card data found; returning user to read a new card.");
    }

    /*
     * For each of the sections in the app, add a tab to the action bar.
     */
    Tab tabA = actionBar.newTab();
    tabA.setText(getString(R.string.TabRead_Title));
    tabA.setTabListener(this);
    actionBar.addTab(tabA);

    // this one will become the CAK tab
    Tab tabB = actionBar.newTab();
    tabB.setText(getString(R.string.TabCert_Title));
    tabB.setTabListener(this);
    actionBar.addTab(tabB);

    // this one will become the CHUID tab
    Tab tabC = actionBar.newTab();
    tabC.setText(getString(R.string.TabChuid_Title));
    tabC.setTabListener(this);
    actionBar.addTab(tabC);

    // this one will become the APDU log tab
    // only set up the tab is the preferences for Show Log = True

    if (showLog) {
        Tab tabD = actionBar.newTab();
        tabD.setText(getString(R.string.TabLog_Title));
        tabD.setTabListener(this);
        actionBar.addTab(tabD);
    }
}

From source file:com.exponent.androidopacitydemo.MainActivity.java

private void enableNfcReaderMode() {
    logger.debug(TAG, "Enabling reader mode");
    NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
    if (nfc != null) {
        // Turn on the NFC reader, registering our CacReader as the callback:
        nfc.enableReaderMode(this, cacReader, NFC_READER_FLAGS, null);
    }/*from w  w  w .  jav  a  2  s .c  om*/
}

From source file:com.nfc.gemkey.MainActivity.java

@Override
public void onCreate(Bundle icicle) {
    if (DEBUG)/*ww w  .ja  va 2s . c  o m*/
        Log.d(TAG, "onCreate");
    super.onCreate(icicle);
    setContentView(R.layout.activity_main);

    mAdapter = NfcAdapter.getDefaultAdapter(this);

    // Create a generic PendingIntent that will be deliver to this activity. The NFC stack
    // will fill in the intent with the details of the discovered tag before delivering to
    // this activity.
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    // Setup an intent filter for all MIME based dispatches
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
    mFilters = new IntentFilter[] { tagDetected };

    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    registerReceiver(mUsbReceiver, filter);

    if (getLastNonConfigurationInstance() != null) {
        Log.i(TAG, "open usb accessory@onCreate");
        mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
        openAccessory(mAccessory);
    }

    buttonLED = (ToggleButton) findViewById(R.id.nfc_btn);
    buttonLED.setBackgroundResource(
            buttonLED.isChecked() ? R.drawable.btn_toggle_yes : R.drawable.btn_toggle_no);
    buttonLED.setOnCheckedChangeListener(mKeyLockListener);

    tagId = (TextView) findViewById(R.id.nfc_tag);
    tagId.setText(R.string.nfc_scan_tag);

    // Avoid NetworkOnMainThreadException
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
            .detectNetwork().penaltyLog().build());

    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
            .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

    setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:ykim81.cs.brown.ykim81.cardreader.CardReaderFragment.java

private void disableReaderMode() {
    Activity activity = getActivity();/*  w w  w  .  ja  va 2s.  c o m*/
    NfcAdapter nfc = NfcAdapter.getDefaultAdapter(activity);
    if (nfc != null) {
        nfc.disableReaderMode(activity);
    }
}

From source file:org.sufficientlysecure.keychain.ui.PassphraseWizardActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getActionBar() != null) {
        getActionBar().setTitle(R.string.unlock_method);
    }/*from   w  ww.  java2  s .  c  om*/

    selectedAction = getIntent().getAction();
    if (savedInstanceState == null) {
        SelectMethods selectMethods = new SelectMethods();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fragmentContainer, selectMethods).commit();
    }
    setContentView(R.layout.passphrase_wizard);

    adapter = NfcAdapter.getDefaultAdapter(this);
    if (adapter != null) {
        pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, PassphraseWizardActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        writeTagFilters = new IntentFilter[] { tagDetected };
    }
}

From source file:com.exponent.androidopacitydemo.MainActivity.java

private void disableNfcReaderMode() {
    logger.debug(TAG, "Disabling reader mode");
    NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
    if (nfc != null) {
        nfc.disableReaderMode(this);
    }// ww w . j a  v  a 2s.c  om
}

From source file:com.example.android.nfcprovisioning.NfcProvisioningFragment.java

@Override
public void onStart() {
    super.onStart();
    Activity activity = getActivity();//from   w w  w.j  a  v a 2  s.c om
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity);
    if (adapter != null) {
        adapter.setNdefPushMessageCallback(this, activity);
    }
    getLoaderManager().initLoader(LOADER_PROVISIONING_VALUES, null, this);
}

From source file:org.schabi.terminightor.NightKillerActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nightkiller);

    final Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    window.addFlags(/*from   w  w  w . j a v  a 2  s .com*/
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

    Bundle a = getIntent().getExtras();
    alarmId = a.getLong(Alarm.ID);
    alarmLabel = a.getString(Alarm.NAME);
    expectedNfcId = a.getByteArray(Alarm.NFC_TAG_ID);

    innerWave = (ImageView) findViewById(R.id.inner_wave_alarm);
    outerWave = (ImageView) findViewById(R.id.outer_wave_alarm);
    alarmLabelView = (TextView) findViewById(R.id.alarm_label_alarm);
    alarmLabelView.setText(alarmLabel);

    nfcAdapter = NfcAdapter.getDefaultAdapter(this);

    ignoreNfcTagId = PreferenceManager.getDefaultSharedPreferences(this)
            .getBoolean(this.getString(R.string.ignoreNfcId), false);

    Log.d(TAG, Long.toString(alarmId));
}

From source file:de.yazo_games.mensaguthaben.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Log.i(TAG, "activity started");

    FragmentManager fm = getSupportFragmentManager();

    valueFragment = (ValueFragment) fm.findFragmentByTag(VALUE_TAG);
    if (valueFragment == null) {
        valueFragment = new ValueFragment();
    }//  w  w w .j a v  a 2 s .c o m
    fm.beginTransaction().replace(R.id.main, valueFragment, VALUE_TAG).commit();

    if (getIntent().getAction().equals(ACTION_FULLSCREEN)) {
        ValueData valueData = (ValueData) getIntent().getSerializableExtra(EXTRA_VALUE);
        valueFragment.setValueData(valueData);

        setResult(0);

    }

    Boolean autostart = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("autostart", true);
    AutostartRegister.register(getPackageManager(), autostart);

    Toolbar t = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(t);
    ViewCompat.setTransitionName(t, "toolbar");

    mAdapter = NfcAdapter.getDefaultAdapter(this);
    mIntentFilter = new IntentFilter("android.nfc.action.ADAPTER_STATE_CHANGED");

    // Create a generic PendingIntent that will be deliver to this activity.
    // The NFC stack
    // will fill in the intent with the details of the discovered tag before
    // delivering to
    // this activity.
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    // Setup an intent filter
    IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    mFilters = new IntentFilter[] { tech, };
    mTechLists = new String[][] { new String[] { IsoDep.class.getName(), NfcA.class.getName() } };

    if (getIntent().getAction().equals(ACTION_FULLSCREEN) && !hasNewData) {
        ValueData valueData = (ValueData) getIntent().getSerializableExtra(EXTRA_VALUE);
        Log.w(TAG, "restoring data for fullscreen");
        valueFragment.setValueData(valueData);

    }
}