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:be.brunoparmentier.wifikeyshare.ui.activities.WifiNetworkActivity.java

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from w  ww  .ja v a 2  s  .c o m

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    wifiNetwork = (WifiNetwork) getIntent().getSerializableExtra(KEY_WIFI_NETWORK);

    if (wifiNetwork.needsPassword()) {
        wifiNetworkId = getIntent().getIntExtra(KEY_NETWORK_ID, -1);
        showWifiPasswordDialog();
    }

    writeTagDialog = new AlertDialog.Builder(this).setTitle(getString(R.string.write_to_tag))
            .setMessage(getString(R.string.write_to_tag_msg))
            .setNegativeButton(getString(R.string.action_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    disableTagWriteMode();
                    dialogInterface.dismiss();
                }
            }).setCancelable(false).create();

    isInWriteMode = false;
    getSupportActionBar().setTitle(wifiNetwork.getSsid());
    nfcAdapter = NfcAdapter.getDefaultAdapter(this);

    if (isNfcAvailable()) {
        initializeNfcStateChangeListener();
        setupForegroundDispatch();
        nfcAdapter.setNdefPushMessage(NfcUtils.generateNdefMessage(wifiNetwork), this);
    }
}

From source file:edu.cmu.mpcs.dashboard.TagViewer.java

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

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

    Intent intent = this.getIntent();
    writeContent = intent.getStringExtra("writeContent");

    mLoginButton = new LoginButton(getApplicationContext());

    // if(flag == true)

    Log.d("TAG_VIEWER", "writeConent:" + writeContent);
    // setContentView(R.layout.tag_viewer);
    mNfcPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    // mTagContent = (LinearLayout) findViewById(R.id.list);
    // mTitle = (TextView) findViewById(R.id.title);

    Log.d("TAG_VIEWER", "Utility.mFacebook is " + Utility.mFacebook);
    if (Utility.mFacebook == null) {
        InitializeLogin = true;/*from   w  ww  .j  av  a  2 s. co m*/

    }
    // Create the Facebook Object using the app id.
    edu.cmu.mpcs.dashboard.Utility.mFacebook = new Facebook(APP_ID);
    // Instantiate the asynrunner object for asynchronous api calls.
    edu.cmu.mpcs.dashboard.Utility.mAsyncRunner = new AsyncFacebookRunner(
            edu.cmu.mpcs.dashboard.Utility.mFacebook);

    Log.d("TAG_VIEWER", "in oncreate in TagViewer is session valid?:" + Utility.mFacebook.isSessionValid());

    mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);

    if (APP_ID == null) {
        Util.showAlert(this, "Warning",
                "Facebook Applicaton ID must be " + "specified before running this example: see FbAPIs.java");
        return;
    }

    SessionStore.restore(Utility.mFacebook, this);
    SessionEvents.addAuthListener(new FbAPIsAuthListener());
    SessionEvents.addLogoutListener(new FbAPIsLogoutListener());
    // SessionEvents.r

    if (Utility.mFacebook.isSessionValid()) {
        requestUserData();

    }

    // TODO do something about - dont call resolve intent by
    // default.
    if (writeContent == null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        Log.d("TAG_VIEWER", "in OnCreate Before reading");
        loginIntent = intent;

        if (InitializeLogin) { /*
                               * This is if we come to tag viewer without
                               * having started dashboard activity
                               */
            mLoginButton.initializeFbLogin();
        } else { /* This is we if read the tag while in dashboard! */
            resolveIntent(intent);

        }
        // mLoginButton.performLogout();

    } else {
        Log.d("TAG_VIEWER", "Before creating alert dialog");
        builder = new AlertDialog.Builder(TagViewer.this);
        dialog = builder.create();
        builder.setTitle("Touch tag to write").setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                Log.d("TAG_VIEWER", "On cancel called");
                disableTagWriteMode();

            }
        }).create();
        dialog.setTitle("touch tag to write");
        dialog.show();
        dialog.setOnDismissListener(new OnDismissListener() {

            public void onDismiss(DialogInterface dialog) {
                // TODO Auto-generated method stub
                Log.d("TAG_VIEWER", "On dismiss called");
                disableTagWriteMode();

            }
        });
        // builder.setCancelable(true);
        // builder.setOnCancelListener(new
        // DialogInterface.OnCancelListener() {
        // public void onCancel(DialogInterface dialog) {
        // Log.d("TAG_VIEWER","On cancel called");
        // disableTagWriteMode();
        //
        // }
        // }).create().show();
    }

    // Tag writing mode
    if (writeContent != null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        Log.d("TAG_VIEWER", "in Oncreate Before writing");

        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        try {
            WriteToTag.write(detectedTag, writeContent);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.d("TAG_VIEWER", "in on create, writing to tag");
    }
    Log.d("TAG_VIEWER", "in create");

}

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

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

    try {// w w w . jav  a 2  s .com
        // creating pending intent:
        PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        // creating intent receiver for NFC events:
        IntentFilter filter = new IntentFilter();
        filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);

        // enabling foreground dispatch for getting intent from NFC event:
        if (mNfcAdapter == null) {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

            if (mNfcAdapter != null) {
                UsefulBits.showSnackbar(this, coordinatorLayout, R.string.nfc_register, Snackbar.LENGTH_SHORT);
            } else {
                UsefulBits.showSnackbar(this, coordinatorLayout, R.string.nfc_not_supported,
                        Snackbar.LENGTH_SHORT);
            }
        }
        if (mNfcAdapter != null)
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, new IntentFilter[] { filter },
                    this.techList);
    } catch (Exception ex) {
        Log.e(this.getClass().getSimpleName(), ex.getMessage());
    }
}

From source file:foundme.uniroma2.it.professore.HomeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    context = this;

    swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeView.setEnabled(false);//from  ww w.ja  v  a2s  . com

    modeCallBack = new ActionMode.Callback() {

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.edit:
                if (!toEdit.equalsIgnoreCase(Variables_it.NO_COURSE)) {
                    Intent i = new Intent(HomeActivity.this, EditCourseActivity.class);
                    i.putExtra(Variables_it.COURSE, toEdit);
                    i.putExtra(Variables_it.NAME, name);
                    startActivity(i);
                }
                toEdit = null;
                mode.finish(); // Automatically exists the action mode, when the user selects this action
                break;
            case R.id.delete:
                if (!toEdit.equalsIgnoreCase(Variables_it.NO_COURSE)) {
                    try {
                        manageCourse(name, toEdit);
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                toEdit = null;
                mode.finish();
                break;
            }
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
            viewList.setBackgroundColor(Color.TRANSPARENT);
            mode = null;
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.setTitle(Variables_it.OPTION);
            mode.getMenuInflater().inflate(R.menu.context_menu, menu);
            return true;
        }
    };

    Bundle passed = getIntent().getExtras();
    name = passed.getString(Variables_it.NAME);
    TAGRead = passed.getString(Variables_it.TAG);

    imgUniroma2 = (ImageButton) findViewById(R.id.ivLogo2);
    imgUniroma2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(Variables_it.SITE_TV));
            startActivity(browserIntent);
        }
    });

    nfctest = (TextView) findViewById(R.id.tvNFC);
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

    if (mNfcAdapter == null) {
        Toast.makeText(this, Variables_it.NFC_UNSUPPORTED, Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    if (!mNfcAdapter.isEnabled()) {
        Toast.makeText(this, Variables_it.NFC_DISABLED, Toast.LENGTH_LONG).show();
    }

    lvCourses = (ListView) findViewById(R.id.lvCourses);

    if (name != null /*&& courses == null*/) {
        try {
            getCourse(true);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    profName = (TextView) findViewById(R.id.tvUserName);
    profName.setText(name);
    nfctest.setText(TAGRead);
    handleIntent(getIntent());
}

From source file:org.hopestarter.wallet.ui.RequestCoinsFragment.java

@Override
public void onAttach(final Activity activity) {
    super.onAttach(activity);

    this.activity = (AbstractBindServiceActivity) activity;
    this.application = (WalletApplication) activity.getApplication();
    this.config = application.getConfiguration();
    this.wallet = application.getWallet();
    this.loaderManager = getLoaderManager();
    this.clipboardManager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
    this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    this.nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
}

From source file:com.coinblesk.client.MainActivity.java

@Override
protected void onResume() {
    super.onResume();
    if (NfcAdapter.getDefaultAdapter(this) != null) {
        NfcAdapter.getDefaultAdapter(this).setNdefPushMessage(null, this);
    }/*from   www. j  a  v a2  s  .c  o  m*/
    registerPaymentRequestReceiver();
}

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

@TargetApi(14)
private void createNdefPushMessageCallback() {
    NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mNfcAdapter != null) {
        mNfcAdapter.setNdefPushMessageCallback(new CreateNdefMessageCallback() {
            @Override/* w  w  w  .j  a v a2s .  c om*/
            public NdefMessage createNdefMessage(NfcEvent event) {
                return new NdefMessage(new NdefRecord[] {
                        new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                                "application/vnd.net.eledge.android.europeana.search".getBytes(), new byte[0],
                                searchController.getPortalUrl().getBytes()),
                        NdefRecord.createApplicationRecord(getPackageName()) });
            }
        }, this);
    }
}

From source file:de.gadc.moneybeam.MoneyBeamActivity.java

/**
 * This method handles the NFC registration and sets the callback.
 *//*  w w w  .j a v  a2s.  c o m*/
private void registerNFC() {
    nfcAdapter = NfcAdapter.getDefaultAdapter(this);

    if (nfcAdapter == null) {
        Toast.makeText(this, R.string.nfc_not_available, Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    nfcAdapter.setNdefPushMessageCallback(this, this);
}

From source file:com.example.multi_ndef.Frag_Write.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.write);/* w ww .  j ava 2 s. c o  m*/

    mWriteTagButton = (Button) findViewById(R.id.write);
    ViewPager pager = (ViewPager) findViewById(R.id.viewPager);

    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    pager.setOffscreenPageLimit(8);

    initListener();

    ma = (CNFCInterface) getApplication();
    // grab our NFC Adapter
    mAdapter = NfcAdapter.getDefaultAdapter(this);

}

From source file:org.ounl.lifelonglearninghub.mediaplayer.cast.refplayer.NFCVideoBrowserActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate() is called");

    VideoCastManager.checkGooglePlayServices(this);
    setContentView(R.layout.video_browser);

    mCastManager = CastApplication.getCastManager(this);

    // -- Adding MiniController
    mMini = (MiniController) findViewById(R.id.miniController1);
    mCastManager.addMiniController(mMini);

    mCastConsumer = new VideoCastConsumerImpl() {

        @Override// w w  w . j a  va2 s  .  c om
        public void onFailed(int resourceId, int statusCode) {

        }

        @Override
        public void onConnectionSuspended(int cause) {
            Log.d(TAG, "onConnectionSuspended() was called with cause: " + cause);
            org.ounl.lifelonglearninghub.mediaplayer.cast.refplayer.utils.Utils
                    .showToast(NFCVideoBrowserActivity.this, R.string.connection_temp_lost);
        }

        @Override
        public void onConnectivityRecovered() {
            org.ounl.lifelonglearninghub.mediaplayer.cast.refplayer.utils.Utils
                    .showToast(NFCVideoBrowserActivity.this, R.string.connection_recovered);
        }

        @Override
        public void onCastDeviceDetected(final RouteInfo info) {
            if (!CastPreference.isFtuShown(NFCVideoBrowserActivity.this) && mIsHoneyCombOrAbove) {
                CastPreference.setFtuShown(NFCVideoBrowserActivity.this);

                Log.d(TAG, "Route is visible: " + info);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (mediaRouteMenuItem.isVisible()) {
                            Log.d(TAG, "Cast Icon is visible: " + info.getName());
                            showFtu();
                        }
                    }
                }, 1000);
            }
        }
    };

    setupActionBar();

    mCastManager.reconnectSessionIfPossible(this, false);

    //
    // NFC
    //      
    resolveIntent(getIntent());
    mDialog = new AlertDialog.Builder(this).setNeutralButton("Ok", null).create();

    mAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mAdapter == null) {
        showMessage(R.string.error, R.string.no_nfc);
    }
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    mNdefPushMessage = new NdefMessage(
            new NdefRecord[] { buildTextRecord("Message from NFC Reader :-)", Locale.ENGLISH, true) });

}