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.securekey.sdk.sample.ReadCardActivity.java

private void disableForegroundDispatch() {
    Log.i("SDKSample", "disable foreground dispatch");
    if (NfcAdapter.getDefaultAdapter(this) != null) {
        try {//from w  w w  . j  a  v a2s.  c  om
            NfcAdapter.getDefaultAdapter(this).disableForegroundDispatch(this);
        } catch (Exception e) {
            Log.i("SDKSample", "disableForegroundDispatch failed = " + e.getMessage());
        }
    }
}

From source file:com.nxp.nfc_demo.activities.MainActivity.java

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

    // Application package name to be used by the AAR record
    PACKAGE_NAME = getApplicationContext().getPackageName();
    String languageToLoad = "en";
    Locale locale = new Locale(languageToLoad);
    Locale.setDefault(locale);/*from  w  w w  .  jav a  2  s  . co m*/
    Configuration config = new Configuration();
    config.locale = locale;
    getBaseContext().getResources().updateConfiguration(config,
            getBaseContext().getResources().getDisplayMetrics());
    setContentView(R.layout.activity_main);
    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup();
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
    mTabsAdapter.addTab(mTabHost.newTabSpec("leds").setIndicator(getString(R.string.leds)), LedFragment.class,
            null);
    mTabsAdapter.addTab(mTabHost.newTabSpec("ndef").setIndicator(getString(R.string.ndefs)), NdefFragment.class,
            null);
    mTabsAdapter.addTab(mTabHost.newTabSpec("ntag_rf").setIndicator(getString(R.string.ntag_rf_text)),
            SpeedTestFragment.class, null);
    mTabsAdapter.addTab(mTabHost.newTabSpec("config").setIndicator(getString(R.string.settings)),
            ConfigFragment.class, null);

    // set current Tag to the Speedtest, so it loads the values
    if (savedInstanceState != null) {
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
    }
    // Get App version
    appVersion = "";
    try {
        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        appVersion = pInfo.versionName;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    // Board firmware version
    boardFirmwareVersion = "Unknown";

    // Notifier to be used for the demo changing
    mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            if (demo.isReady()) {
                demo.finishAllTasks();
                if (tabId.equalsIgnoreCase("leds") && demo.isConnected()) {
                    launchDemo(tabId);
                }
            }
            mTabsAdapter.onTabChanged(tabId);
        }
    });
    // When we open the application by default we set the status to disabled (we don't know the product yet)
    mAuthStatus = AuthStatus.Disabled.getValue();

    // Initialize the demo in order to handle tab change events
    demo = new Ntag_I2C_Demo(null, this, null, 0);
    mAdapter = NfcAdapter.getDefaultAdapter(this);
    setNfcForeground();
    checkNFC();
}

From source file:com.tananaev.passportreader.MainActivity.java

@Override
protected void onResume() {
    super.onResume();

    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
    Intent intent = new Intent(getApplicationContext(), this.getClass());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    String[][] filter = new String[][] { new String[] { "android.nfc.tech.IsoDep" } };
    adapter.enableForegroundDispatch(this, pendingIntent, null, filter);
}

From source file:org.irmacard.androidmanagement.CredentialListActivity.java

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

    // Pass the list of CredentialPackages on to the ListFragement
    Intent intent = getIntent();/*  w w  w . j a va2 s  . c o  m*/
    @SuppressWarnings("unchecked")
    ArrayList<CredentialPackage> credentials = (ArrayList<CredentialPackage>) intent
            .getSerializableExtra(WaitingForCardActivity.EXTRA_CREDENTIAL_PACKAGES);
    setCredentials(credentials);

    @SuppressWarnings("unchecked")
    ArrayList<LogEntry> logs = (ArrayList<LogEntry>) intent
            .getSerializableExtra(WaitingForCardActivity.EXTRA_LOG_ENTRIES);
    setLogs(logs);

    Tag tag = (Tag) intent.getParcelableExtra(WaitingForCardActivity.EXTRA_TAG);
    setTag(tag);

    cardPin = (String) intent.getSerializableExtra(WaitingForCardActivity.EXTRA_CARD_PIN);
    cardVersion = (CardVersion) intent.getSerializableExtra(WaitingForCardActivity.EXTRA_CARD_VERSION);

    setContentView(R.layout.activity_credential_list);

    if (findViewById(R.id.credential_detail_container) != null) {
        // The detail container view will be present only in the
        // large-screen layouts (res/values-large and
        // res/values-sw600dp). If this view is present, then the
        // activity should be in two-pane mode.
        mTwoPane = true;

        // In two-pane mode, list items should be given the
        // 'activated' state when touched.
        ((MenuFragment) getSupportFragmentManager().findFragmentById(R.id.credential_menu_fragment))
                .setTwoPaneMode(true);

        InitFragment initFragment = new InitFragment();
        getSupportFragmentManager().beginTransaction().replace(R.id.credential_detail_container, initFragment)
                .commit();

        Log.i("blaat", "Simulating initial click!!");
        ((MenuFragment) getSupportFragmentManager().findFragmentById(R.id.credential_menu_fragment))
                .simulateListClick(0);

        // Do not show action bar in two-pane mode
        getActionBar().hide();
    }

    // NFC stuff
    nfcA = NfcAdapter.getDefaultAdapter(getApplicationContext());
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    // Setup an intent filter for all TECH based dispatches
    IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    mFilters = new IntentFilter[] { tech };

    // Setup a tech list for all IsoDep cards
    mTechLists = new String[][] { new String[] { IsoDep.class.getName() } };
}

From source file:org.croudtrip.fragments.join.JoinDrivingFragment.java

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

    //Register local broadcasts
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(joinRequestExpiredReceiver,
            new IntentFilter(Constants.EVENT_JOIN_REQUEST_EXPIRED));

    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(nfcScannedReceiver,
            new IntentFilter(Constants.EVENT_NFC_TAG_SCANNED));

    IntentFilter filter = new IntentFilter();
    filter.addAction(Constants.EVENT_SECONDARY_DRIVER_ACCEPTED);
    filter.addAction(Constants.EVENT_SECONDARY_DRIVER_DECLINED);
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(secondaryDriverAcceptedDeclinedReceiver,
            filter);//ww w .j  av a  2 s.c  om

    //Register nfc adapter
    nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
    if (nfcAdapter != null) {
        nfcPendingIntent = PendingIntent.getActivity(getActivity(), 0,
                new Intent(getActivity(), getActivity().getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                0);
    }

    //Initialize colors for different routes on the map
    colors = new ArrayList<>();
    colors.add(Color.BLUE);
    colors.add(Color.GREEN);
    colors.add(Color.RED);
    colors.add(Color.YELLOW);

    shadesOfGray = new ArrayList<>();
    shadesOfGray.add(Color.GRAY);
    shadesOfGray.add(Color.DKGRAY);
    shadesOfGray.add(Color.LTGRAY);
}

From source file:com.sigilance.CardEdit.MainActivity.java

/**
 * Receive new NFC Intents to this activity only by enabling foreground dispatch.
 * This can only be done in onResume!/*from ww  w .ja  va 2 s.c om*/
 */
public void enableNfcForegroundDispatch() {
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mNfcAdapter == null) {
        return;
    }
    Intent nfcI = new Intent(this, getClass())
            .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent nfcPendingIntent = PendingIntent.getActivity(this, 0, nfcI,
            PendingIntent.FLAG_CANCEL_CURRENT);
    IntentFilter[] writeTagFilters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED) };

    try {
        mNfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, writeTagFilters, null);
    } catch (IllegalStateException e) {
        Toast.makeText(this, "NfcForegroundDispatch Error!", Toast.LENGTH_LONG).show();
    }
}

From source file:com.tananaev.passportreader.MainActivity.java

@Override
protected void onPause() {
    super.onPause();

    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
    adapter.disableForegroundDispatch(this);
}

From source file:com.brq.wallet.activity.receive.ReceiveCoinsActivity.java

@TargetApi(16)
protected void shareByNfc() {
    if (Build.VERSION.SDK_INT < 16) {
        // the function isNdefPushEnabled is only available for SdkVersion >= 16
        // We would be theoretically able to push the message over Ndef, but it is not
        // possible to check if Ndef/NFC is available or not - so dont try it at all, if
        // SdkVersion is too low
        return;/* ww  w .  ja  v  a  2 s  .co  m*/
    }

    NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
    if (nfc != null && nfc.isNdefPushEnabled()) {
        nfc.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
            @Override
            public NdefMessage createNdefMessage(NfcEvent event) {
                NdefRecord uriRecord = NdefRecord.createUri(getPaymentUri());
                return new NdefMessage(new NdefRecord[] { uriRecord });
            }
        }, this);
        ivNfc.setVisibility(View.VISIBLE);
        ivNfc.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.showSimpleMessageDialog(ReceiveCoinsActivity.this,
                        getString(R.string.nfc_payment_request_hint));
            }
        });
    } else {
        ivNfc.setVisibility(View.GONE);
    }
}

From source file:de.uni_koblenz_landau.apow.LoginActivity.java

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

    // Re-attach Tasks.
    TaskActivityReference.getInstance().attach(LoginTask.TASK_ID, this);
    TaskActivityReference.getInstance().attach(SetupTask.TASK_ID, this);
    TaskActivityReference.getInstance().attach(NFCTagReaderTask.TASK_ID, this);
    TaskActivityReference.getInstance().attach(LocationWebTask.TASK_ID, this);

    // Create UI references.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(this.getResources().getColor(R.color.color_primary_dark));
    }/*  ww  w.j  ava 2 s . c  om*/
    setContentView(R.layout.login_activity);
    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    if (mToolbar != null) {
        setSupportActionBar(mToolbar);
    }

    mSetupLocationView = (Spinner) findViewById(R.id.login_setup_locations);
    mStatusView = findViewById(R.id.login_status);
    mStatusMessageView = (TextView) findViewById(R.id.login_status_message);
    mLoginFormView = findViewById(R.id.login_login);
    mLoginPasswordView = (EditText) findViewById(R.id.login_login_password);
    mLoginPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                login(textView);
                return true;
            }
            return false;
        }
    });
    mLoginNFCText = (TextView) findViewById(R.id.login_login_nfc);
    mSetupFormView = findViewById(R.id.login_setup);
    mSetupNFCText = (TextView) findViewById(R.id.login_setup_nfc);

    mSetupDatabasePasswordView = (EditText) findViewById(R.id.login_setup_database_password);
    mSetupDatabaseConfirmView = (EditText) findViewById(R.id.login_setup_database_password_confirm);
    mSetupServerUsernameView = (EditText) findViewById(R.id.login_login_server_user);
    mSetupServerPasswordView = (EditText) findViewById(R.id.login_login_server_password);

    //mFirstRun = true;
    mFirstRun = getSharedPreferences(Constants.PREFERENCE, MODE_PRIVATE).getBoolean(ARG_FIRST_RUN, true);
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

    // Restore UI from saved instance or load data.
    if (savedInstanceState != null) {
        mNFCTag = savedInstanceState.getString(ARG_NFC);
        mNFCTextDrawable = savedInstanceState.getInt(ARG_NFC_STATE);
        mAutoSignOffDismissed = savedInstanceState.getBoolean(ARG_AUTO_SIGN_OFF_DISMISSED);
        mProgress = savedInstanceState.getBoolean(ARG_PROGRESS);
        if (mFirstRun) {
            mLocations = savedInstanceState.getParcelableArrayList(ARG_LOCATIONS);
            if (mLocations != null) {
                ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<>(this,
                        android.R.layout.simple_spinner_item, mLocations);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                mSetupLocationView.setAdapter(adapter);
                mSetupLocationView.setSelection(savedInstanceState.getInt(ARG_LOCATION_SELECTION));
            }
        }
    } else {
        mProgress = false;
        mAutoSignOffDismissed = false;
        mNFCTag = "";
        mNFCTextDrawable = R.drawable.empty;
        if (mFirstRun) {
            loadLocations();
        }
    }
    mLoginNFCText.setCompoundDrawablesWithIntrinsicBounds(0, 0, mNFCTextDrawable, 0);
    mSetupNFCText.setCompoundDrawablesWithIntrinsicBounds(0, 0, mNFCTextDrawable, 0);

    if (mFirstRun) {
        mSetupFormView.setVisibility(View.VISIBLE);
        mLoginFormView.setVisibility(View.GONE);
        this.setTitle(R.string.login_setup_title);
    } else {
        mSetupFormView.setVisibility(View.GONE);
        mLoginFormView.setVisibility(View.VISIBLE);
        this.setTitle(R.string.login_login_title);
    }

    if (getIntent().getBooleanExtra(ARG_AUTO_LOGOUT, false) && !mAutoSignOffDismissed) {
        SignedOffDialog dialog = new SignedOffDialog();
        dialog.show(getSupportFragmentManager(), SIGNED_OFF_DIALOG_ID);
        mAutoSignOffDismissed = true;
    }
    showProgress(mProgress);
    setNFCState();
}

From source file:it.imwatch.nfclottery.MainActivity.java

/**
 * Determines if the NFC adapter is available on the device.
 *
 * @param showUi True to show some feedback to the user when needed, false
 *               to avoid showing feedbacks
 *
 * @return Returns true if the NFC adapter is available, false otherwise
 *//*from  ww  w .jav a2 s. com*/
private boolean isNfcAvailable(boolean showUi) {
    if (mNfcAdapter == null) {
        // Try to retrieve the default NFC adapter (might not have been initialized yet)
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    }

    if (mNfcAdapter == null) {
        // This means the device doesn't have NFC, and we don't support this: finish here
        if (showUi) {
            Toast.makeText(this, getString(R.string.error_nfc_not_available), Toast.LENGTH_LONG).show();
        }
        return false;
    }

    return true;
}