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:org.esupportail.nfctagdroid.NfcTacDroidActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ESUP_NFC_TAG_SERVER_URL = getEsupNfcTagServerUrl(getApplicationContext());
    //To keep session for desfire async requests
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    LocalStorage.getInstance(getApplicationContext());
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getApplicationContext()));
    setContentView(R.layout.activity_main);
    mAdapter = NfcAdapter.getDefaultAdapter(this);
    checkHardware(mAdapter);// w  w  w . jav  a2 s . com
    localStorageDBHelper = LocalStorage.getInstance(this.getApplicationContext());
    String numeroId = localStorageDBHelper.getValue("numeroId");
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String imei = telephonyManager.getDeviceId();
    url = ESUP_NFC_TAG_SERVER_URL + "/nfc-index?numeroId=" + numeroId + "&imei=" + imei + "&macAddress="
            + getMacAddr() + "&apkVersion=" + getApkVersion();
    view = (WebView) this.findViewById(R.id.webView);
    view.clearCache(true);
    view.addJavascriptInterface(new LocalStorageJavaScriptInterface(this.getApplicationContext()),
            "AndroidLocalStorage");
    view.addJavascriptInterface(new AndroidJavaScriptInterface(this.getApplicationContext()), "Android");

    view.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (progress == 100) {
                AUTH_TYPE = localStorageDBHelper.getValue("authType");
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            log.info("Webview console message : " + consoleMessage.message());
            return false;
        }

    });

    view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            view.reload();
            return true;
        }
    });
    view.getSettings().setAllowContentAccess(true);
    WebSettings webSettings = view.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDatabasePath(this.getFilesDir().getParentFile().getPath() + "/databases/");

    view.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }

    });

    view.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
        }
    });

    view.loadUrl(url);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

From source file:ru.tinkoff.acquiring.sdk.nfc.NfcCardScanActivity.java

private void initNfc() {
    nfc = NfcAdapter.getDefaultAdapter(this);
    if (nfc == null) {
        return;//w  w  w . j a  va2s. c o  m
    }

    nfcIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    if (!nfc.isEnabled()) {
        Toast.makeText(this, R.string.acq_nfc_need_enable, Toast.LENGTH_SHORT).show();
        startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), REQUEST_CODE_SETTINGS);
    }
}

From source file:com.codebutler.farebot.activities.AddKeyActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_key);
    getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT);

    findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
        @Override/* ww w.  j  a va 2s .c o  m*/
        public void onClick(View view) {
            setResult(RESULT_CANCELED);
            finish();
        }
    });

    findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String keyType = ((RadioButton) findViewById(R.id.is_key_a)).isChecked()
                    ? ClassicSectorKey.TYPE_KEYA
                    : ClassicSectorKey.TYPE_KEYB;

            new BetterAsyncTask<Void>(AddKeyActivity.this, true, false) {
                @Override
                protected Void doInBackground() throws Exception {
                    ClassicCardKeys keys = ClassicCardKeys.fromDump(keyType, mKeyData);

                    ContentValues values = new ContentValues();
                    values.put(KeysTableColumns.CARD_ID, mTagId);
                    values.put(KeysTableColumns.CARD_TYPE, mCardType);
                    values.put(KeysTableColumns.KEY_DATA, keys.toJSON().toString());

                    getContentResolver().insert(CardKeyProvider.CONTENT_URI, values);

                    return null;
                }

                @Override
                protected void onResult(Void unused) {
                    Intent intent = new Intent(AddKeyActivity.this, KeysActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();
                }
            }.execute();
        }
    });

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

    Utils.checkNfcEnabled(this, mNfcAdapter);

    Intent intent = getIntent();
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    mPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_VIEW)
            && getIntent().getData() != null) {
        try {
            InputStream stream = getContentResolver().openInputStream(getIntent().getData());
            mKeyData = IOUtils.toByteArray(stream);
        } catch (IOException e) {
            Utils.showErrorAndFinish(this, e);
        }
    } else {
        finish();
    }
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    mSharedPrefs = new SharedPrefUtil(this);
    if (mSharedPrefs.darkThemeEnabled())
        setTheme(R.style.AppThemeDark);/*from   w  w  w .  j ava 2 s.c  om*/
    else
        setTheme(R.style.AppTheme);
    if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage()))
        UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage());

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nfc_settings);
    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
    if (mSharedPrefs.darkThemeEnabled()) {
        coordinatorLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.background_dark));
    }

    if (getSupportActionBar() != null)
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    this.setTitle(R.string.category_nfc);

    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);
    }

    domoticz = new Domoticz(this, AppController.getInstance().getRequestQueue());
    nfcList = mSharedPrefs.getNFCList();
    adapter = new NFCAdapter(this, nfcList, this);

    createListView();
}

From source file:org.adictolinux.mfcclone.MainActivity.java

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

    mTitle = mDrawerTitle = getTitle();//ww  w .j a  va  2 s . co m
    menuTitles = getResources().getStringArray(R.array.menu_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // set a custom shadow that overlays the main content when the drawer
    // opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, menuTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open, /* "open drawer" description for accessibility */
            R.string.drawer_close /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to
            // onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to
            // onPrepareOptionsMenu()
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    mAdapter = NfcAdapter.getDefaultAdapter(this);
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    mFilters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) };

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

    // Escondemos el teclado hasta que el user toca una entrada de texto
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    if (savedInstanceState == null) {
        replaceFragment(new ForceKeysFragment(), 0);
    }
}

From source file:com.codebutler.farebot.activity.AddKeyActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_key);
    getWindow().setLayout(WRAP_CONTENT, MATCH_PARENT);

    findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
        @Override/*from w ww . j  av  a2  s.  c  o m*/
        public void onClick(View view) {
            setResult(RESULT_CANCELED);
            finish();
        }
    });

    findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String keyType = ((RadioButton) findViewById(R.id.is_key_a)).isChecked()
                    ? ClassicSectorKey.TYPE_KEYA
                    : ClassicSectorKey.TYPE_KEYB;

            new BetterAsyncTask<Void>(AddKeyActivity.this, true, false) {
                @Override
                protected Void doInBackground() throws Exception {
                    ClassicCardKeys keys = ClassicCardKeys.fromDump(keyType, mKeyData);

                    ContentValues values = new ContentValues();
                    values.put(KeysTableColumns.CARD_ID, mTagId);
                    values.put(KeysTableColumns.CARD_TYPE, mCardType);
                    values.put(KeysTableColumns.KEY_DATA, keys.toJSON().toString());

                    getContentResolver().insert(CardKeyProvider.CONTENT_URI, values);

                    return null;
                }

                @Override
                protected void onResult(Void unused) {
                    Intent intent = new Intent(AddKeyActivity.this, KeysActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();
                }
            }.execute();
        }
    });

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

    Utils.checkNfcEnabled(this, mNfcAdapter);

    Intent intent = getIntent();
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    mPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_VIEW)
            && getIntent().getData() != null) {
        // Request permission for storage first
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    STORAGE_PERMISSION_CALLBACK);
        } else {
            // Just read the key file
            readKeyFile();
        }

    } else {
        finish();
    }
}

From source file:net.networksaremadeofstring.rhybudd.WriteNFCActivity.java

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

    BugSenseHandler.initAndStartSession(WriteNFCActivity.this, "44a76a8c");

    setContentView(R.layout.write_tag_activity);

    try {/* w ww. jav  a  2s .  c  o  m*/
        getActionBar().setSubtitle(getString(R.string.NFCTitle));
        getActionBar().setDisplayHomeAsUpEnabled(true);
    } catch (Exception gab) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", gab);
    }

    //Quick test
    try {
        UID = getIntent().getExtras().getString(PAYLOAD_UID).replace("/zport/dmd/Devices/", "");

        aaRecord = NdefRecord.createApplicationRecord("net.networksaremadeofstring.rhybudd");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            //idRecord = NdefRecord.createExternal("rhybudd:tag", "z", UID.getBytes(Charset.forName("US-ASCII")));
            idRecord = NdefRecord.createMime("application/vnd.rhybudd.device", UID.getBytes());
        } else {
            idRecord = NdefRecord.createUri("rhybudd://" + UID);
        }

        ((TextView) findViewById(R.id.SizesText)).setText("This payload is "
                + (aaRecord.toByteArray().length + idRecord.toByteArray().length)
                + " bytes.\n\nAn ultralight can store up to 46 bytes.\nAn Ultralight C or NTAG203 can store up to 137 bytes.\nDespite the name a 1K can only store up to 716 bytes.");
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", e);
        try {
            Toast.makeText(this, "Sorry there was error parsing the passed UID, we cannot continue.",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception t) {
            BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", t);
        }

        finish();
    }

    try {
        mAdapter = NfcAdapter.getDefaultAdapter(this);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate getDefaultAdapter", e);
        mAdapter = null;
    }

    try {
        pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate pendingIntent", e);
    }

    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

    try {
        ndef.addDataType("*/*"); /* Handles all MIME based dispatches.
                                    You should specify only the ones that you need. */
    } catch (IntentFilter.MalformedMimeTypeException e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", e);
        throw new RuntimeException("fail", e);
    }

    try {
        IntentFilter td = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        intentFiltersArray = new IntentFilter[] { ndef, td };

        techListsArray = new String[][] { new String[] { NfcF.class.getName(), NfcA.class.getName(),
                Ndef.class.getName(), NdefFormatable.class.getName() } };
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate IntentFilter", e);
    }

    CreateHandlers();
}

From source file:com.support.android.designlibdemo.EditContactActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit);

    Intent intent = getIntent();/*from w ww . j  a  va  2 s  . com*/
    //contact= getIntent().getParcelableExtra("ContactTag");
    cheeseName = intent.getStringExtra(EXTRA_NAME);

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Typeface fontAwesomeFont = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf");

    Button CallTel1 = (Button) findViewById(R.id.CallTel1);

    Button CallTel2 = (Button) findViewById(R.id.CallTel2);

    Button SendMail = (Button) findViewById(R.id.SendMail1);

    Button LocateSociete1 = (Button) findViewById(R.id.LocateSociete1);

    Button LocateSite1 = (Button) findViewById(R.id.LocateSite1);

    Button LocateAdres1 = (Button) findViewById(R.id.LocateAdres1);

    CallTel1.setTypeface(fontAwesomeFont);

    CallTel2.setTypeface(fontAwesomeFont);
    SendMail.setTypeface(fontAwesomeFont);

    LocateAdres1.setTypeface(fontAwesomeFont);

    LocateSite1.setTypeface(fontAwesomeFont);

    LocateSociete1.setTypeface(fontAwesomeFont);

    _name = ((EditText) findViewById(R.id.Nom));

    _prenom = ((EditText) findViewById(R.id.Prenom));

    _phone_number = ((EditText) findViewById(R.id.Tel1));

    _email = ((EditText) findViewById(R.id.Mail1));

    _fixe = ((EditText) findViewById(R.id.Tel2));

    _societe = ((EditText) findViewById(R.id.Societe1));

    _adresse = ((EditText) findViewById(R.id.Adres1));

    _profile = ((EditText) findViewById(R.id.Position));

    _site = ((EditText) findViewById(R.id.Site1));

    _skype = ((EditText) findViewById(R.id.Skype1));

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    Log.e("Search Query: ", "  hellooo " + cheeseName);

    handleIntent(getIntent());
    Common.setNfcAdapter(NfcAdapter.getDefaultAdapter(this));
    reader = Common.checkForTagAndCreateReader(this);
    if (cheeseName.compareTo("Editer") == 0)
        readTag(0);
}

From source file:com.example.mynsocial.BluetoothChat.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (D)//  w w w.j a v  a2  s  .co  m
        Log.e(TAG, "+++ ON CREATE +++");

    // Set up the window layout
    setContentView(R.layout.activity_fight);
    TextView text_touch = (TextView) findViewById(R.id.texttouch);

    title = (TextView) findViewById(R.id.titletext);

    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    SharedPreferences sp = this.getSharedPreferences("loginPrefs", MODE_PRIVATE);
    fb_id = sp.getString("fb_id", fb_id);
    inputText = mBluetoothAdapter.getAddress();//??MAC
    NdefMessage message = create_RTD_TEXT_NdefMessage(inputText);
    mNfcAdapter.setNdefPushMessage(message, this);

}