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.evandroid.musica.fragment.LyricsViewFragment.java

@TargetApi(16)
private void beamLyrics(final Lyrics lyrics, Activity activity) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
    if (nfcAdapter != null && nfcAdapter.isEnabled()) {
        if (lyrics.getText() != null) {
            nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
                @Override//w  ww . j av a2 s  .c  om
                public NdefMessage createNdefMessage(NfcEvent event) {
                    try {
                        byte[] payload = lyrics.toBytes(); // whatever data you want to send
                        NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                                "application/lyrics".getBytes(), new byte[0], payload);
                        return new NdefMessage(new NdefRecord[] { record, // your data
                                NdefRecord.createApplicationRecord("com.geecko.QuickLyric"), // the "application record"
                        });
                    } catch (IOException e) {
                        return null;
                    }
                }
            }, activity);
        }
    }
}

From source file:org.openhab.habdroid.ui.OpenHABMainActivity.java

@Override
public void onResume() {
    Log.d(TAG, "onResume()");
    super.onResume();
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, ((Object) this).getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    if (NfcAdapter.getDefaultAdapter(this) != null)
        NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this, pendingIntent, null, null);
    if (!TextUtils.isEmpty(mNfcData)) {
        Log.d(TAG, "We have NFC data from launch");
    }//from  w ww  . j a v  a  2 s . co m
    pagerAdapter.setColumnsNumber(getResources().getInteger(R.integer.pager_columns));
    FragmentManager fm = getSupportFragmentManager();
    stateFragment = (StateRetainFragment) fm.findFragmentByTag("stateFragment");
    // If state fragment doesn't exist (which means fresh start of the app)
    // or if state fragment returned 0 fragments (this happens sometimes and we don't yet
    // know why, so this is a workaround
    // start over the whole process
    Boolean startOver = stateFragment == null || stateFragment.getFragmentList().size() == 0;
    if (startOver || !NetworkConnectivityInfo.currentNetworkConnectivityInfo(this)
            .equals(mStartedWithNetworkConnectivityInfo)) {
        resetStateFragmentAfterResume(fm);
    } else {
        // If connectivity type changed while we were in background
        // Restart the whole process
        if (!NetworkConnectivityInfo.currentNetworkConnectivityInfo(this)
                .equals(mStartedWithNetworkConnectivityInfo)) {
            Log.d(TAG, "Connectivity type changed while I was out, or zero fragments found, need to restart");
            resetStateFragmentAfterResume(fm);
            // Clean up any existing fragments
            pagerAdapter.clearFragmentList();
            // Clean up title
            this.setTitle(R.string.app_name);
            return;
        }
        // If state fragment exists and contains something then just restore the fragments
        Log.d(TAG, "State fragment found");
        pagerAdapter.setFragmentList(stateFragment.getFragmentList());
        Log.d(TAG, String.format("Loaded %d fragments", stateFragment.getFragmentList().size()));
        pager.setCurrentItem(stateFragment.getCurrentPage());
    }
    if (!TextUtils.isEmpty(mPendingNfcPage)) {
        openNFCPageIfPending();
    }

    checkFullscreen();
}

From source file:com.irccloud.android.activity.ImageViewerActivity.java

private void loadImage(String urlStr) {
    try {/* w w  w  .  j  a  v  a 2  s.  co m*/
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB && urlStr.startsWith("https://")) {
            GingerbreadImageProxy proxy = new GingerbreadImageProxy();
            proxy.init();
            proxy.start();
            urlStr = String.format("http://127.0.0.1:%d/%s", proxy.getPort(), urlStr);
        }
        URL url = new URL(urlStr);

        mImage.loadDataWithBaseURL(null, "<!DOCTYPE html>\n"
                + "<html><head><style>html, body, table { height: 100%; width: 100%; background-color: #000;}</style></head>\n"
                + "<body>\n" + "<table><tr><td>" + "<img src='" + url.toString()
                + "' width='100%' onerror='Android.imageFailed()' onclick='Android.imageClicked()' style='background-color: #fff;'/>\n"
                + "</td></tr></table>" + "</body>\n" + "</html>", "text/html", "UTF-8", null);

        try {
            if (Build.VERSION.SDK_INT >= 16) {
                NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
                if (nfc != null) {
                    nfc.setNdefPushMessage(new NdefMessage(NdefRecord.createUri(urlStr)), this);
                }
            }
        } catch (Exception e) {
        }
    } catch (Exception e) {
        fail();
    }
}

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

private void setPreferences() {
    final android.preference.SwitchPreference MultiServerPreference = (android.preference.SwitchPreference) findPreference(
            "enableMultiServers");
    android.preference.Preference ServerSettings = findPreference("server_settings");
    android.preference.Preference PermissionsSettings = findPreference("permissionssettings");
    android.preference.Preference NotificationLogged = findPreference("notification_show_logs");
    android.preference.Preference fetchServerConfig = findPreference("server_force_fetch_config");
    android.preference.Preference resetApplication = findPreference("reset_settings");
    android.preference.ListPreference displayLanguage = (ListPreference) findPreference("displayLanguage");
    final android.preference.Preference registrationId = findPreference("notification_registration_id");
    android.preference.Preference GeoSettings = findPreference("geo_settings");
    android.preference.SwitchPreference WearPreference = (android.preference.SwitchPreference) findPreference(
            "enableWearItems");
    android.preference.Preference NFCPreference = findPreference("nfc_settings");
    android.preference.Preference QRCodePreference = findPreference("qrcode_settings");
    android.preference.Preference SpeechPreference = findPreference("speech_settings");
    android.preference.SwitchPreference EnableNFCPreference = (android.preference.SwitchPreference) findPreference(
            "enableNFC");
    android.preference.SwitchPreference EnableQRCodePreference = (android.preference.SwitchPreference) findPreference(
            "enableQRCode");
    android.preference.SwitchPreference EnableSpeechPreference = (android.preference.SwitchPreference) findPreference(
            "enableSpeech");
    android.preference.SwitchPreference EnableTalkBackPreference = (android.preference.SwitchPreference) findPreference(
            "talkBack");
    MultiSelectListPreference drawerItems = (MultiSelectListPreference) findPreference("enable_menu_items");
    @SuppressWarnings("SpellCheckingInspection")
    android.preference.SwitchPreference AlwaysOnPreference = (android.preference.SwitchPreference) findPreference(
            "alwayson");
    @SuppressWarnings("SpellCheckingInspection")
    android.preference.PreferenceScreen preferenceScreen = (android.preference.PreferenceScreen) findPreference(
            "settingsscreen");
    android.preference.PreferenceCategory premiumCategory = (android.preference.PreferenceCategory) findPreference(
            "premium_category");
    android.preference.Preference premiumPreference = findPreference("premium_settings");
    NotificationsMultiSelectListPreference notificationsMultiSelectListPreference = (NotificationsMultiSelectListPreference) findPreference(
            "suppressNotifications");
    NotificationsMultiSelectListPreference alarmMultiSelectListPreference = (NotificationsMultiSelectListPreference) findPreference(
            "alarmNotifications");
    android.preference.SwitchPreference ThemePreference = (android.preference.SwitchPreference) findPreference(
            "darkTheme");
    android.preference.Preference FingerPrintSettingsPreference = findPreference("SecuritySettings");
    android.preference.SwitchPreference FingerPrintPreference = (android.preference.SwitchPreference) findPreference(
            "enableSecurity");

    if (!BuildConfig.DEBUG) {
        PreferenceCategory oAndroidAutoCategory = (android.preference.PreferenceCategory) findPreference(
                "androidautocategory");
        PreferenceScreen oNotificationScreen = (android.preference.PreferenceScreen) findPreference(
                "notificationscreen");
        oNotificationScreen.removePreference(oAndroidAutoCategory);
    }/*from  w w  w . j  a va 2  s . com*/

    List<String> notifications = mSharedPrefs.getReceivedNotifications();
    if (notifications == null || notifications.size() <= 0) {
        notificationsMultiSelectListPreference.setEnabled(false);
        alarmMultiSelectListPreference.setEnabled(false);
    } else {
        notificationsMultiSelectListPreference.setEnabled(true);
        alarmMultiSelectListPreference.setEnabled(true);
    }

    PermissionsSettings
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    permissionHelper.openSettingsScreen();
                    return true;
                }
            });

    drawerItems.setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
            try {
                final HashSet selectedDrawerItems = (HashSet) newValue;
                if (selectedDrawerItems.size() < 1) {
                    showSnackbar(mContext.getString(R.string.error_atLeastOneItemInDrawer));
                    return false;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
            return true;
        }
    });

    ThemePreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_theme));
                        return false;
                    } else {
                        ((SettingsActivity) getActivity()).reloadSettings();
                        return true;
                    }
                }
            });

    MultiServerPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.multi_server));
                        return false;
                    }
                    return true;
                }
            });

    ServerSettings.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(android.preference.Preference preference) {
            if (!MultiServerPreference.isChecked()) {
                Intent intent = new Intent(mContext, ServerSettingsActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(mContext, ServerListSettingsActivity.class);
                startActivity(intent);
            }
            return true;
        }
    });

    FingerPrintSettingsPreference
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    mContext.startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS));
                    return true;
                }
            });

    fetchServerConfig
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    UsefulBits.getServerConfigForActiveServer(mContext, true, new ConfigReceiver() {
                        @Override
                        public void onReceiveConfig(ConfigInfo settings) {
                            showSnackbar(mContext.getString(R.string.fetched_server_config_success));
                        }

                        @Override
                        public void onError(Exception error) {
                            showSnackbar(mContext.getString(R.string.fetched_server_config_failed));
                        }
                    }, null);
                    return true;
                }
            });

    displayLanguage
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    showRestartMessage();
                    return true;
                }
            });

    registrationId.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(android.preference.Preference preference) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!PermissionsUtil.canAccessDeviceState(mContext)) {
                    permissionHelper.request(PermissionsUtil.INITIAL_DEVICE_PERMS);
                } else {
                    pushGCMRegistrationIds();
                }
            } else {
                pushGCMRegistrationIds();
            }
            return true;
        }
    });

    GeoSettings.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(android.preference.Preference preference) {
            if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                showPremiumSnackbar(getString(R.string.geofence));
                return false;
            } else {
                Intent intent = new Intent(mContext, GeoSettingsActivity.class);
                startActivity(intent);
                return true;
            }
        }
    });

    EnableNFCPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_nfc));
                        return false;
                    }

                    if (NfcAdapter.getDefaultAdapter(mContext) == null) {
                        showSnackbar(mContext.getString(R.string.nfc_not_supported));
                        return false;
                    }
                    return true;
                }
            });

    EnableQRCodePreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_QRCode));
                        return false;
                    }

                    return true;
                }
            });

    EnableSpeechPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_Speech));
                        return false;
                    }
                    return true;
                }
            });

    EnableTalkBackPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_talk_back));
                        return false;
                    }
                    return true;
                }
            });

    NFCPreference.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(android.preference.Preference preference) {
            if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                showPremiumSnackbar(getString(R.string.category_nfc));
                return false;
            } else {
                Intent intent = new Intent(mContext, NFCSettingsActivity.class);
                startActivity(intent);
                return true;
            }
        }
    });

    QRCodePreference
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_QRCode));
                        return false;
                    } else {
                        Intent intent = new Intent(mContext, QRCodeSettingsActivity.class);
                        startActivity(intent);
                        return true;
                    }
                }
            });

    SpeechPreference
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_Speech));
                        return false;
                    } else {
                        Intent intent = new Intent(mContext, SpeechSettingsActivity.class);
                        startActivity(intent);
                        return true;
                    }
                }
            });

    WearPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_wear));
                        return false;
                    }
                    return true;
                }
            });

    AlwaysOnPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.always_on_title));
                        return false;
                    }
                    return true;
                }
            });

    NotificationLogged
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    //show dialog
                    List<String> logs = mSharedPrefs.getLoggedNotifications();
                    if (logs != null && logs.size() > 0) {
                        Collections.reverse(logs);
                        new MaterialDialog.Builder(mContext)
                                .title(mContext.getString(R.string.notification_show_title))
                                .items((CharSequence[]) logs.toArray(new String[0])).show();
                    } else
                        UsefulBits.showSimpleToast(mContext, getString(R.string.notification_show_nothing),
                                Toast.LENGTH_LONG);
                    return true;
                }
            });

    //noinspection PointlessBooleanExpression
    if (!BuildConfig.LITE_VERSION) {
        preferenceScreen.removePreference(premiumCategory);
    } else {
        premiumPreference
                .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(android.preference.Preference preference) {
                        String packageID = mContext.getPackageName() + ".premium";
                        try {
                            startActivity(new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("market://details?id=" + packageID)));
                        } catch (android.content.ActivityNotFoundException ignored) {
                            startActivity(new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("https://play.google.com/store/apps/details?id=" + packageID)));
                        }

                        return true;
                    }
                });
    }

    resetApplication
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        new MaterialDialog.Builder(mContext).title(R.string.category_Reset)
                                .content(R.string.are_you_sure).positiveText(R.string.ok)
                                .negativeText(R.string.cancel)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @SuppressLint("NewApi")
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog,
                                            @NonNull DialogAction which) {
                                        ((ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE))
                                                .clearApplicationUserData();
                                    }
                                }).show();
                    } else {
                        startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
                    }
                    return true;
                }
            });

    FingerPrintPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @SuppressLint("NewApi")
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object o) {
                    if (mSharedPrefs.isStartupSecurityEnabled())
                        return true;
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_startup_security));
                        return false;
                    } else {
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                            UsefulBits.showSimpleToast(mContext, getString(R.string.fingerprint_not_supported),
                                    Toast.LENGTH_LONG);
                            return false;
                        }
                        if (!PermissionsUtil.canAccessFingerprint(mContext)) {
                            permissionHelper.request(PermissionsUtil.INITIAL_FINGERPRINT_PERMS);
                        } else {
                            FingerprintManager fingerprintManager = (FingerprintManager) mContext
                                    .getSystemService(Context.FINGERPRINT_SERVICE);
                            if (ActivityCompat.checkSelfPermission(mContext,
                                    Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
                                return false;
                            }
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                if (!fingerprintManager.isHardwareDetected()) {
                                    return false;
                                } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                                    UsefulBits.showSimpleToast(mContext,
                                            getString(R.string.fingerprint_not_setup_in_android),
                                            Toast.LENGTH_LONG);
                                    return false;
                                } else {
                                    new MaterialDialog.Builder(mContext)
                                            .title(R.string.category_startup_security)
                                            .content(R.string.fingerprint_sure).positiveText(R.string.ok)
                                            .negativeText(R.string.cancel)
                                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                                @Override
                                                public void onClick(@NonNull MaterialDialog dialog,
                                                        @NonNull DialogAction which) {
                                                    mSharedPrefs.setStartupSecurityEnabled(true);
                                                    ((SettingsActivity) getActivity()).reloadSettings();
                                                }
                                            }).show();

                                    return false;
                                }
                            }
                        }
                    }
                    return false;
                }
            });
}

From source file:me.willowcheng.makerthings.ui.OpenHABMainActivity.java

@Override
public void onResume() {
    Log.d(TAG, "onResume()");
    super.onResume();
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, ((Object) this).getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    if (NfcAdapter.getDefaultAdapter(this) != null)
        NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this, pendingIntent, null, null);
    if (!TextUtils.isEmpty(mNfcData)) {
        Log.d(TAG, "We have NFC data from launch");
    }/*from   w w w . j a v  a  2 s  . com*/
    pagerAdapter.setColumnsNumber(getResources().getInteger(R.integer.pager_columns));
    FragmentManager fm = getSupportFragmentManager();
    stateFragment = (StateRetainFragment) fm.findFragmentByTag("stateFragment");
    // If state fragment doesn't exist (which means fresh start of the app)
    // or if state fragment returned 0 fragments (this happens sometimes and we don't yet
    // know why, so this is a workaround
    // start over the whole process
    if (stateFragment == null || stateFragment.getFragmentList().size() == 0) {
        stateFragment = null;
        stateFragment = new StateRetainFragment();
        fm.beginTransaction().add(stateFragment, "stateFragment").commit();
        mOpenHABTracker = new OpenHABTracker(this, openHABServiceType, mServiceDiscoveryEnabled);
        mStartedWithNetworkConnectivityInfo = NetworkConnectivityInfo.currentNetworkConnectivityInfo(this);
        mOpenHABTracker.start();
        // If state fragment exists and contains something then just restore the fragments
    } else {
        Log.d(TAG, "State fragment found");
        // If connectivity type changed while we were in background
        // Restart the whole process
        // TODO: this must be refactored to remove duplicate code!
        if (!NetworkConnectivityInfo.currentNetworkConnectivityInfo(this)
                .equals(mStartedWithNetworkConnectivityInfo)) {
            Log.d(TAG, "Connectivity type changed while I was out, or zero fragments found, need to restart");
            // Clean up any existing fragments
            pagerAdapter.clearFragmentList();
            stateFragment.getFragmentList().clear();
            stateFragment = null;
            // Clean up title
            this.setTitle(R.string.app_name);
            stateFragment = new StateRetainFragment();
            fm.beginTransaction().add(stateFragment, "stateFragment").commit();
            mOpenHABTracker = new OpenHABTracker(this, openHABServiceType, mServiceDiscoveryEnabled);
            mStartedWithNetworkConnectivityInfo = NetworkConnectivityInfo.currentNetworkConnectivityInfo(this);
            mOpenHABTracker.start();
            return;
        }
        pagerAdapter.setFragmentList(stateFragment.getFragmentList());
        Log.d(TAG, String.format("Loaded %d fragments", stateFragment.getFragmentList().size()));
        pager.setCurrentItem(stateFragment.getCurrentPage());
        Log.d(TAG, String.format("Loaded current page = %d", stateFragment.getCurrentPage()));
    }
    if (!TextUtils.isEmpty(mPendingNfcPage)) {
        openNFCPageIfPending();
    }

    checkFullscreen();
}

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

@Override
protected void onPause() {
    super.onPause();
    App.activityPaused();/* w w w .  j  a v  a 2 s .co m*/
    if (receiver != null && receiverRegistered) {
        unregisterReceiver(receiver);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
        receiverRegistered = false;
    }
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (nfcAdapter != null)
        nfcAdapter.disableForegroundDispatch(this);
    AppBarLayout appBarLayout = (AppBarLayout) findViewById(id.appbar);
    appBarLayout.removeOnOffsetChangedListener(this);
}

From source file:de.syss.MifareClassicTool.Common.java

/**
 * Check if the device supports the Mifare Classic technology.
 * In order to do so, there is a first check ensure the device actually has
 * a NFC hardware (if not, {@link #mUseAsEditorOnly} is set to true).
 * After this, this function will check if there are files
 * like "/dev/bcm2079x-i2c" or "/system/lib/libnfc-bcrm*". Files like
 * these are indicators for a NFC controller manufactured by Broadcom.
 * Broadcom chips don't support Mifare Classic.
 * @return True if the device supports Mifare Classic. False otherwise.
 * @see #mHasMifareClassicSupport/* w  w  w .  ja  v  a 2s.  c  om*/
 * @see #mUseAsEditorOnly
 */
public static boolean hasMifareClassicSupport() {
    if (mHasMifareClassicSupport != 0) {
        return mHasMifareClassicSupport == 1;
    }

    // Check for the MifareClassic class.
    // It is most likely there on all NFC enabled phones.
    // Therefore this check is not needed.
    /*
    try {
    Class.forName("android.nfc.tech.MifareClassic");
    } catch( ClassNotFoundException e ) {
    // Class not found. Devices does not support Mifare Classic.
    return false;
    }
    */

    // Check if ther is any NFC hardware at all.
    if (NfcAdapter.getDefaultAdapter(mAppContext) == null) {
        mUseAsEditorOnly = true;
        mHasMifareClassicSupport = -1;
        return false;
    }

    // Check if there is the NFC device "bcm2079x-i2c".
    // Chips by Broadcom don't support Mifare Classic.
    // This could fail because on a lot of devices apps don't have
    // the sufficient permissions.
    File device = new File("/dev/bcm2079x-i2c");
    if (device.exists()) {
        mHasMifareClassicSupport = -1;
        return false;
    }

    // Check if there is the NFC device "pn544".
    // The PN544 NFC chip is manufactured by NXP.
    // Chips by NXP support Mifare Classic.
    device = new File("/dev/pn544");
    if (device.exists()) {
        mHasMifareClassicSupport = 1;
        return true;
    }

    // Check if there are NFC libs with "brcm" in their names.
    // "brcm" libs are for devices with Broadcom chips. Broadcom chips
    // don't support Mifare Classic.
    File libsFolder = new File("/system/lib");
    File[] libs = libsFolder.listFiles();
    for (File lib : libs) {
        if (lib.isFile() && lib.getName().startsWith("libnfc") && lib.getName().contains("brcm")
        // Add here other non NXP NFC libraries.
        ) {
            mHasMifareClassicSupport = -1;
            return false;
        }
    }

    mHasMifareClassicSupport = 1;
    return true;
}

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

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

    //Log.e("onCreate","onCreate");
    setHasOptionsMenu(true);/* w ww . java 2  s. co  m*/
    if (null != getArguments() && getArguments().containsKey("checkZPImmediately"))
        checkZPImmediately = getArguments().getBoolean("checkZPImmediately");

    // Check for available NFC Adapter
    mNfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());

    if (null != mNfcAdapter) {
        // Register callback
        mNfcAdapter.setNdefPushMessageCallback(this, getActivity());
    }

    checkZPHandler = new Handler() {
        public void handleMessage(Message msg) {
            try {
                if (null != progressbar) {
                    progressbar.startAnimation(
                            AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
                    progressbar.setVisibility(View.GONE);
                }
            } catch (NullPointerException npe) {
                npe.printStackTrace();
            } catch (Exception e) {
                BugSenseHandler.sendExceptionMessage("PushSettingsFragment", "checkZPHandler", e);
            }

            switch (msg.what) {
            /*case RhybuddHandlers.msg_push_show_undo:
            {
                FilterKey.setText(msg.getData().getString("newfilterkey"));
                try
                {
                    if(null == undoMenuItem)
                    {
                        menu.add(Menu.NONE,MENU_UNDO,Menu.NONE,"Undo");
                        undoMenuItem = menu.findItem(MENU_UNDO);
                        undoMenuItem.setIcon(R.drawable.ic_action_content_undo);
                        undoMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                    }
                    
                    getActivity().invalidateOptionsMenu();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                    BugSenseHandler.sendExceptionMessage("PushSettingsFragment","processIntent",e);
                }
            }
            break;*/

            case RhybuddHandlers.msg_generic_http_transport_error: {
                try {
                    Toast.makeText(getActivity(), getActivity().getString(R.string.PushZPNoHost),
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("PushSettingsFragment",
                            "checkZPHandler msg_generic_http_transport_error", e);
                }
            }
                break;

            case RhybuddHandlers.msg_zp_is_installed: {
                try {
                    hasZenPack = true;
                    ZPInstalledImg.setImageResource(R.drawable.ic_acknowledged);
                    ZPDeviceRegistered.setImageResource(R.drawable.ic_unacknowledged);
                    ZPVersion.setText("1.0.1");
                    enabledSwitch.setEnabled(hasZenPack);
                    registerWithZenPack.setEnabled(hasZenPack);

                    if (checkZPImmediately) {
                        RegisterWithZenPack();
                    } else {
                        checkZenPack.setVisibility(View.VISIBLE);
                        registerWithZenPack.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("PushSettingsFragment",
                            "checkZPHandler msg_zp_is_installed", e);
                }
            }
                break;

            case RhybuddHandlers.msg_zp_not_installed: {
                try {
                    hasZenPack = false;
                    ZPInstalledImg.setImageResource(R.drawable.ic_unacknowledged);
                    ZPDeviceRegistered.setImageResource(R.drawable.ic_unacknowledged);
                    ZPVersion.setText("----");
                    enabledSwitch.setEnabled(hasZenPack);
                    registerWithZenPack.setEnabled(hasZenPack);
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("PushSettingsFragment",
                            "checkZPHandler msg_zp_not_installed", e);
                }
            }
                break;

            case RhybuddHandlers.msg_zp_registered: {
                try {
                    ZPDeviceRegistered.setImageResource(R.drawable.ic_acknowledged);
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("PushSettingsFragment",
                            "checkZPHandler msg_zp_registered", e);
                }
            }
                break;

            case RhybuddHandlers.msg_zp_not_registered: {
                try {
                    ZPDeviceRegistered.setImageResource(R.drawable.ic_unacknowledged);
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("PushSettingsFragment",
                            "checkZPHandler msg_zp_not_registered", e);
                }
            }
                break;
            }
        }
    };

    getIDhandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RhybuddHandlers.msg_generic_success: {
                try {
                    String pushKey = msg.getData().getString(ZenossAPI.PREFERENCE_PUSHKEY);

                    progressbar.setVisibility(View.GONE);
                    //PushKey.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
                    //PushKey.setVisibility(View.VISIBLE);
                    PushKeyDesc.startAnimation(
                            AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
                    PushKeyDesc.setVisibility(View.VISIBLE);
                    //PushKey.setText(pushKey);

                    SharedPreferences.Editor editor = PreferenceManager
                            .getDefaultSharedPreferences(getActivity()).edit();
                    editor.putString(ZenossAPI.PREFERENCE_PUSHKEY, pushKey);
                    editor.commit();
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("PushSettingsFragment",
                            "getIDhandler msg_generic_success", e);
                }
            }
                break;

            case RhybuddHandlers.msg_json_error: {
                try {
                    progressbar.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), getString(R.string.JSONExceptionMessage), Toast.LENGTH_LONG)
                            .show();
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("PushSettingsFragment", "getIDhandler msg_json_error",
                            e);
                }
            }
                break;

            case RhybuddHandlers.msg_generic_http_transport_error: {
                try {
                    progressbar.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), getString(R.string.HttpTransportExceptionMessage),
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("PushSettingsFragment", "getIDhandler msg_json_error",
                            e);
                }
            }
                break;

            case RhybuddHandlers.msg_generic_failure: {
                try {
                    progressbar.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), getString(R.string.GenericExceptionMessage),
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("PushSettingsFragment",
                            "getIDhandler msg_generic_failure", e);
                }
            }
                break;
            }
        }
    };
}

From source file:net.zjy.zxcardumper.Common.java

/**
 * Check if the device supports the MIFARE Classic technology.
 * In order to do so, there is a first check ensure the device actually has
 * a NFC hardware (if not, {@link #mUseAsEditorOnly} is set to true).
 * After this, this function will check if there are files
 * like "/dev/bcm2079x-i2c" or "/system/lib/libnfc-bcrm*". Files like
 * these are indicators for a NFC controller manufactured by Broadcom.
 * Broadcom chips don't support MIFARE Classic.
 * @return True if the device supports MIFARE Classic. False otherwise.
 * @see #mHasMifareClassicSupport//from  ww w.  j av  a 2 s .c o m
 * @see #mUseAsEditorOnly
 */
public static boolean hasMifareClassicSupport() {
    if (mHasMifareClassicSupport != 0) {
        return mHasMifareClassicSupport == 1;
    }

    // Check for the MifareClassic class.
    // It is most likely there on all NFC enabled phones.
    // Therefore this check is not needed.
    /*
    try {
    Class.forName("android.nfc.tech.MifareClassic");
    } catch( ClassNotFoundException e ) {
    // Class not found. Devices does not support MIFARE Classic.
    return false;
    }
    */

    // Check if ther is any NFC hardware at all.
    if (NfcAdapter.getDefaultAdapter(mAppContext) == null) {
        mUseAsEditorOnly = true;
        mHasMifareClassicSupport = -1;
        return false;
    }

    // Check if there is the NFC device "bcm2079x-i2c".
    // Chips by Broadcom don't support MIFARE Classic.
    // This could fail because on a lot of devices apps don't have
    // the sufficient permissions.
    File device = new File("/dev/bcm2079x-i2c");
    if (device.exists()) {
        mHasMifareClassicSupport = -1;
        return false;
    }

    // Check if there is the NFC device "pn544".
    // The PN544 NFC chip is manufactured by NXP.
    // Chips by NXP support MIFARE Classic.
    device = new File("/dev/pn544");
    if (device.exists()) {
        mHasMifareClassicSupport = 1;
        return true;
    }

    // Check if there are NFC libs with "brcm" in their names.
    // "brcm" libs are for devices with Broadcom chips. Broadcom chips
    // don't support MIFARE Classic.
    File libsFolder = new File("/system/lib");
    File[] libs = libsFolder.listFiles();
    for (File lib : libs) {
        if (lib.isFile() && lib.getName().startsWith("libnfc") && lib.getName().contains("brcm")
        // Add here other non NXP NFC libraries.
        ) {
            mHasMifareClassicSupport = -1;
            return false;
        }
    }

    mHasMifareClassicSupport = 1;
    return true;
}