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.basov.ticketinfo.UI.java

public void displayWelcomeByNFC(WebView wv) {
    Context c = wv.getContext();//w  ww. j  ava  2s.  c o  m
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(c);
    if (adapter == null || !adapter.isEnabled()) {
        setWelcome("w_msg", "<font color=\"darkred\">" + c.getString(R.string.welcome_without_nfc) + "<font>");
    } else {
        setWelcome("w_msg", "<font color=\"darkgreen\">" + c.getString(R.string.welcome_with_nfc) + "<font>");
    }
    displayWelcomeScreen(wv);
}

From source file:com.hybris.mobile.activity.AbstractProductDetailActivity.java

/**
 * Enables Android Beam based NFC Sharing for the specified product code
 * //from  www  .ja  v a  2s.c o  m
 * @param id
 */
private void enableAndroidBeam(String productCode) {
    if (NFCUtil.canNFC(this)) {
        NdefMessage msg = getNDEF(productCode);
        NfcAdapter.getDefaultAdapter(this).setNdefPushMessage(msg, this);
    }
}

From source file:com.piusvelte.taplock.client.core.TapLockSettings.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*w  w  w . j  a  va 2 s.  c om*/
    registerForContextMenu(getListView());
    if (!getPackageName().toLowerCase().contains(PRO)) {
        AdView adView = new AdView(this, AdSize.BANNER, GOOGLE_AD_ID);
        ((LinearLayout) findViewById(R.id.ad)).addView(adView);
        adView.loadAd(new AdRequest());
    }
    //NFC
    mNfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());

}

From source file:org.ulteo.ovd.AndRdpActivity.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void startSession(int screen_width, int screen_height) {
    if (isConnected())
        return;//from   www  . j  a  va2s.  c  o m

    Bundle bundle = getIntent().getExtras();

    if (bundle == null) {
        finish();
        return;
    }

    Point res;
    // check if user has chosen a specific resolution
    if (!Settings.getResolutionAuto(this)) {
        res = Settings.getResolution(this);
    } else {
        res = new Point(screen_width, screen_height);
        // Prefer wide screen
        if (!Settings.getResolutionWide(this) && res.y > res.x) {
            int w = res.x;
            res.x = res.y;
            res.y = w;
        }
    }
    Log.i(Config.TAG, "Resolution: " + res.x + "x" + res.y);

    String gateway_token = null;
    Boolean gateway_mode = bundle.getBoolean(PARAM_GATEWAYMODE);
    if (gateway_mode)
        gateway_token = bundle.getString(PARAM_TOKEN);

    int drives = Properties.REDIRECT_DRIVES_FULL;
    Properties prop = smHandler.getResponseProperties();
    if (prop != null)
        drives = prop.isDrives();

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN
            && bundle.getString(PARAM_SM_URI) != null) {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter != null) {
            NdefRecord rtdUriRecord = NdefRecord.createUri(bundle.getString(PARAM_SM_URI));
            NdefMessage ndefMessage = new NdefMessage(rtdUriRecord);
            nfcAdapter.setNdefPushMessage(ndefMessage, this);
        }
    }

    rdp = new Rdp(res, bundle.getString(PARAM_LOGIN), bundle.getString(PARAM_PASSWD),
            bundle.getString(PARAM_IP), bundle.getInt(PARAM_PORT, SessionManagerCommunication.DEFAULT_RDP_PORT),
            gateway_mode, gateway_token, drives,
            bundle.getString(PARAM_RDPSHELL) == null ? "" : bundle.getString(PARAM_RDPSHELL),
            Settings.getBulkCompression(AndRdpActivity.this), Settings.getConnexionType(AndRdpActivity.this));

    Resources resources = getResources();
    Intent notificationIntent = new Intent(this, AndRdpActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.icon_bw)
            .setContentTitle(resources.getText(R.string.app_name)).setOngoing(true)
            .setContentText(resources.getText(R.string.desktop_session_active)).setContentIntent(pendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, mBuilder.build());

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipChangedListener = new ClipboardManager.OnPrimaryClipChangedListener() {
            @Override
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            public void onPrimaryClipChanged() {
                ClipboardManager clipboard = (ClipboardManager) AndRdpActivity.this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = clipboard.getPrimaryClip();
                String text = clip.getItemAt(0).coerceToText(AndRdpActivity.this).toString();
                if (Config.DEBUG)
                    Log.d(Config.TAG, "Android clipboard : " + text);

                if (isLoggedIn())
                    rdp.sendClipboard(text);
            }
        };
        clipboard.addPrimaryClipChangedListener(clipChangedListener);
    }
}

From source file:org.bohrmeista.chan.ui.activity.BaseActivity.java

/**
 * Set the url that Android Beam and the share action will send.
 *
 * @param url//from   w w  w.j  ava 2  s. c o  m
 */
public void setShareUrl(String url) {
    shareUrl = url;

    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);

    if (adapter != null) {
        NdefRecord record = null;
        try {
            record = NdefRecord.createUri(url);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return;
        }

        NdefMessage message = new NdefMessage(new NdefRecord[] { record });
        try {
            adapter.setNdefPushMessage(message, this);
        } catch (Exception e) {
        }
    }

    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.putExtra(android.content.Intent.EXTRA_TEXT, url);
    share.setType("text/plain");

    if (shareActionProvider != null) {
        shareActionProvider.setShareIntent(share);
    } else {
        pendingShareActionProviderIntent = share;
    }
}

From source file:us.rader.tapset.nfc.ForegroundDispatchActivity.java

/**
 * Initialize the data structures used in conjunction with foreground
 * dispatch//w ww.  ja  v  a 2s.  c  om
 * 
 * @param savedInstanceState
 *            saved state or <code>null</code>
 * 
 * @see FragmentActivity#onCreate(Bundle)
 */
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    adapter = NfcAdapter.getDefaultAdapter(this);
    filters = createIntentFilters();
    Intent intent = new Intent(this, getClass());
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    pendingIntent = PendingIntent.getActivity(this, requestCode, intent, 0);

}

From source file:org.protocoderrunner.apprunner.AppRunnerActivity.java

public void initializeNFC() {

    if (nfcInit == false) {
        PackageManager pm = getPackageManager();
        nfcSupported = pm.hasSystemFeature(PackageManager.FEATURE_NFC);

        if (nfcSupported == false) {
            return;
        }//from w w  w. jav a  2 s.c  o  m

        // cuando esta en foreground
        MLog.d(TAG, "Starting NFC");
        mAdapter = NfcAdapter.getDefaultAdapter(this);
        /*
         * mAdapter.setNdefPushMessageCallback(new
         * NfcAdapter.CreateNdefMessageCallback() {
         *
         * @Override public NdefMessage createNdefMessage(NfcEvent event) {
         * // TODO Auto-generated method stub return null; } }, this, null);
         */

        // Create mContext 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 ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[] { ndef, };

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

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

/**
 * NFC: Initialize NFC sharing if OS and device supports it
 *///from   www .ja  v  a2s.  co  m
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void initNfc(final Uri dataUri) {
    // check if NFC Beam is supported (>= Android 4.1)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {

        // Implementation for the CreateNdefMessageCallback interface
        mNdefCallback = new NfcAdapter.CreateNdefMessageCallback() {
            @Override
            public NdefMessage createNdefMessage(NfcEvent event) {
                /*
                 * When a device receives a push with an AAR in it, the application specified in the AAR is
                 * guaranteed to run. The AAR overrides the tag dispatch system. You can add it back in to
                 * guarantee that this activity starts when receiving a beamed message. For now, this code
                 * uses the tag dispatch system.
                 */
                NdefMessage msg = new NdefMessage(NdefRecord.createMime(Constants.NFC_MIME, mNfcKeyringBytes),
                        NdefRecord.createApplicationRecord(Constants.PACKAGE_NAME));
                return msg;
            }
        };

        // Implementation for the OnNdefPushCompleteCallback interface
        mNdefCompleteCallback = new NfcAdapter.OnNdefPushCompleteCallback() {
            @Override
            public void onNdefPushComplete(NfcEvent event) {
                // A handler is needed to send messages to the activity when this
                // callback occurs, because it happens from a binder thread
                mNfcHandler.obtainMessage(NFC_SENT).sendToTarget();
            }
        };

        // Check for available NFC Adapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter != null) {
            /*
             * Retrieve mNfcKeyringBytes here asynchronously (to not block the UI)
             * and init nfc adapter afterwards.
             * mNfcKeyringBytes can not be retrieved in createNdefMessage, because this process
             * has no permissions to query the Uri.
             */
            AsyncTask<Void, Void, Void> initTask = new AsyncTask<Void, Void, Void>() {
                protected Void doInBackground(Void... unused) {
                    try {
                        Uri blobUri = KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri);
                        mNfcKeyringBytes = (byte[]) mProviderHelper.getGenericData(blobUri,
                                KeychainContract.KeyRingData.KEY_RING_DATA, ProviderHelper.FIELD_TYPE_BLOB);
                    } catch (ProviderHelper.NotFoundException e) {
                        Log.e(Constants.TAG, "key not found!", e);
                    }

                    // no AsyncTask return (Void)
                    return null;
                }

                protected void onPostExecute(Void unused) {
                    // Register callback to set NDEF message
                    mNfcAdapter.setNdefPushMessageCallback(mNdefCallback, ViewKeyActivity.this);
                    // Register callback to listen for message-sent success
                    mNfcAdapter.setOnNdefPushCompleteCallback(mNdefCompleteCallback, ViewKeyActivity.this);
                }
            };

            initTask.execute();
        }
    }
}

From source file:com.brandroidtools.filemanager.activities.NavigationActivity.java

/**
 * {@inheritDoc}/*from w w  w  .  j a v a 2  s .co m*/
 */
@Override
protected void onCreate(Bundle state) {

    if (DEBUG) {
        Log.d(TAG, "NavigationActivity.onCreate"); //$NON-NLS-1$
    }

    // Register the broadcast receiver
    IntentFilter filter = new IntentFilter();
    filter.addAction(FileManagerSettings.INTENT_SETTING_CHANGED);
    filter.addAction(FileManagerSettings.INTENT_FILE_CHANGED);
    filter.addAction(FileManagerSettings.INTENT_THEME_CHANGED);
    registerReceiver(this.mNotificationReceiver, filter);

    //Set the main layout of the activity
    setContentView(R.layout.navigation_pager);

    //Initialize nfc adapter
    NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mNfcAdapter != null && Build.VERSION.SDK_INT > 15) {
        mNfcAdapter.setBeamPushUrisCallback(new NfcAdapter.CreateBeamUrisCallback() {
            @Override
            public Uri[] createBeamUris(NfcEvent event) {
                List<FileSystemObject> selectedFiles = getCurrentNavigationFragment().getSelectedFiles();
                if (selectedFiles.size() > 0) {
                    List<Uri> fileUri = new ArrayList<Uri>();
                    for (FileSystemObject f : selectedFiles) {
                        //Beam ignores folders and system files
                        if (!FileHelper.isDirectory(f) && !FileHelper.isSystemFile(f)) {
                            fileUri.add(Uri.fromFile(new File(f.getFullPath())));
                        }
                    }
                    if (fileUri.size() > 0) {
                        return fileUri.toArray(new Uri[fileUri.size()]);
                    }
                }
                return null;
            }
        }, this);
    }

    //Initialize activity
    init();

    //Initialize viewPager
    initViewPager();

    //Initialize action bar
    mActionBar = getActionBar();
    initTitleActionBar();

    // Apply the theme
    applyTheme();

    // Show welcome message
    showWelcomeMsg();

    //Save state
    super.onCreate(state);
}

From source file:com.geecko.QuickLyric.MainActivity.java

@Override
protected void onResume() {
    super.onResume();
    App.activityResumed();//from  w  w w .j a va  2s .c o m
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (nfcAdapter != null) {
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, ((Object) this).getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndef.addDataType("application/lyrics");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            return;
        }
        IntentFilter[] intentFiltersArray = new IntentFilter[] { ndef, };
        try {
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null);
        } catch (Exception ignored) {
        }
    }
    LyricsViewFragment lyricsViewFragment = (LyricsViewFragment) getFragmentManager()
            .findFragmentByTag(LYRICS_FRAGMENT_TAG);
    if (lyricsViewFragment != null) {
        if (getIntent() == null || getIntent().getAction() == null || getIntent().getAction().equals("")) {
            // fixme executes twice?
            if (!"Storage".equals(lyricsViewFragment.getSource()) && !lyricsViewFragment.searchResultLock)
                lyricsViewFragment.fetchCurrentLyrics(false);
            lyricsViewFragment.checkPreferencesChanges();
        }
    }
    AppBarLayout appBarLayout = (AppBarLayout) findViewById(id.appbar);
    appBarLayout.removeOnOffsetChangedListener(this);
    appBarLayout.addOnOffsetChangedListener(this);
}