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:de.uni_koblenz_landau.apow.PatientListActivity.java

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

    // Re-attach Tasks.
    TaskActivityReference.getInstance().attach(NFCIDReaderTask.TASK_ID, this);

    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(ARG_QUERY)) {
            mSavedQuery = savedInstanceState.getString(ARG_QUERY);
        }//  w  w w . ja v a2s . co m
        if (savedInstanceState.containsKey(ARG_NFC)) {
            mNfcInfoOpen = savedInstanceState.getInt(ARG_NFC);
        }
    }

    setContentView(R.layout.patient_list_activity);

    // Attach child fragment.
    mFragment = (PatientListFragment) getSupportFragmentManager().findFragmentById(R.id.patient_list);

    mNFCInfo = (TextView) findViewById(R.id.patient_list_nfc);

    // Set up NFC.
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

    // Set up navigation drawer.
    String[] navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
    TypedArray navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.color_primary_dark));
    mDrawerOuterLayout = (ScrimInsetsFrameLayout) findViewById(R.id.drawer_outer_layout);
    ArrayList<NavDrawerItem> navDrawerItems = new ArrayList<>();
    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    navDrawerItems
            .add(new NavDrawerItem(navMenuTitles[KEY_SETTINGS], navMenuIcons.getResourceId(KEY_SETTINGS, -1)));
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[KEY_ABOUT], navMenuIcons.getResourceId(KEY_ABOUT, -1)));
    navDrawerItems
            .add(new NavDrawerItem(navMenuTitles[KEY_SIGN_OFF], navMenuIcons.getResourceId(KEY_SIGN_OFF, -1)));
    navMenuIcons.recycle();

    NavDrawerListAdapter adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
    mDrawerList.setAdapter(adapter);
    mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            onDrawerItemSelected(position);
        }
    });
    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    if (mToolbar != null) {
        setSupportActionBar(mToolbar);
    }
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.app_name,
            R.string.app_name) {
        @Override
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerToggle.syncState();
}

From source file:org.chromium.chrome.browser.bookmark.ManageBookmarkActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {//from   w ww  .  ja v  a2s . c  o m
        if (getApplication() instanceof ChromeApplication) {
            ((ChromeApplication) getApplication()).startBrowserProcessesAndLoadLibrariesSync(true);
        }
    } catch (ProcessInitException e) {
        Log.e(TAG, "Unable to load native library.", e);
        ChromeApplication.reportStartupErrorAndExit(e);
        return;
    }
    if (!DeviceFormFactor.isTablet(this)) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    if (savedInstanceState == null) {
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.add(android.R.id.content, generateBaseFragment(), BASE_ADD_EDIT_FRAGMENT_TAG);
        fragmentTransaction.commit();
    } else {
        initializeFragmentState();
    }

    // When adding or removing fragments, ensure the keyboard is hidden if visible as the
    // editing fields are no longer on the screen.
    getFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            UiUtils.hideKeyboard(findViewById(android.R.id.content));
        }
    });
    if (checkPermission(Manifest.permission.NFC, Process.myPid(),
            Process.myUid()) == PackageManager.PERMISSION_GRANTED) {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter != null)
            nfcAdapter.setNdefPushMessage(null, this);
    }
}

From source file:org.droid2droid.test.TestDroid2DroidListFragment.java

@Override
@TargetApi(14)/*from  ww  w  . ja va 2s . c  o  m*/
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (VERSION.SDK_INT > VERSION_CODES.ICE_CREAM_SANDWICH) {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);
        if (mNfcAdapter != null) {
            mNfcAdapter.setNdefPushMessageCallback(
                    // Hook for compatibility
                    new CreateNdefMessageCallback() {
                        @Override
                        public NdefMessage createNdefMessage(NfcEvent event) {
                            return TestDroid2DroidListFragment.this.createNdefMessage(event);
                        }

                    }, activity);

        }
    }
}

From source file:org.chromium.chrome.browser.preferences.Preferences.java

@SuppressFBWarnings("DM_EXIT")
@SuppressLint("InlinedApi")
@Override//from w  w  w .  j a v  a2s. c  om
protected void onCreate(Bundle savedInstanceState) {
    ensureActivityNotExported();

    // The browser process must be started here because this Activity may be started explicitly
    // from Android notifications, when Android is restoring Preferences after Chrome was
    // killed, or for tests. This should happen before super.onCreate() because it might
    // recreate a fragment, and a fragment might depend on the native library.
    try {
        ((ChromeApplication) getApplication()).startBrowserProcessesAndLoadLibrariesSync(true);
    } catch (ProcessInitException e) {
        Log.e(TAG, "Failed to start browser process.", e);
        // This can only ever happen, if at all, when the activity is started from an Android
        // notification (or in tests). As such we don't want to show an error messsage to the
        // user. The application is completely broken at this point, so close it down
        // completely (not just the activity).
        System.exit(-1);
        return;
    }

    super.onCreate(savedInstanceState);

    mIsNewlyCreated = savedInstanceState == null;

    String initialFragment = getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT);
    Bundle initialArguments = getIntent().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
    boolean displayHomeAsUp = getIntent().getBooleanExtra(EXTRA_DISPLAY_HOME_AS_UP, true);

    if (displayHomeAsUp)
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // This must be called before the fragment transaction below.
    workAroundPlatformBugs();

    // If savedInstanceState is non-null, then the activity is being
    // recreated and super.onCreate() has already recreated the fragment.
    if (savedInstanceState == null) {
        if (initialFragment == null)
            initialFragment = MainPreferences.class.getName();
        Fragment fragment = Fragment.instantiate(this, initialFragment, initialArguments);
        getFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();
    }

    if (checkPermission(Manifest.permission.NFC, Process.myPid(),
            Process.myUid()) == PackageManager.PERMISSION_GRANTED) {
        // Disable Android Beam on JB and later devices.
        // In ICS it does nothing - i.e. we will send a Play Store link if NFC is used.
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter != null)
            nfcAdapter.setNdefPushMessage(null, this);
    }

    Resources res = getResources();
    ApiCompatibilityUtils.setTaskDescription(this, res.getString(R.string.app_name),
            BitmapFactory.decodeResource(res, R.mipmap.app_icon),
            ApiCompatibilityUtils.getColor(res, R.color.default_primary_color));
}

From source file:ch.bfh.instacircle.NetworkActiveActivity.java

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

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

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override/*from   w ww.j a v  a  2  s . co  m*/
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        actionBar
                .addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }

    // Handle the change of the Wifi configuration
    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    adhoc = new AdhocWifiManager(wifi);
    wifiapmanager = new WifiAPManager();
    registerReceiver(wifiReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));

    // Is NFC available on this device?
    nfcAvailable = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC);

    // only set up the NFC stuff if NFC is also available
    if (nfcAvailable) {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter.isEnabled()) {

            // Setting up a pending intent that is invoked when an NFC tag
            // is tapped on the back
            pendingIntent = PendingIntent.getActivity(this, 0,
                    new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

            nfcIntentFilter = new IntentFilter();
            nfcIntentFilter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
            nfcIntentFilter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
            intentFiltersArray = new IntentFilter[] { nfcIntentFilter };
        } else {
            nfcAvailable = false;
        }
    }
}

From source file:net.zjy.zxcardumper.Activities.MainMenu.java

/**
 * Check for NFC hardware, MIFARE Classic support and for external storage.
 * If the directory structure and the std. keys files is not already there
 * it will be created. Also, at the first run of this App, a warning
 * notice and a donate message will be displayed.
 * @see #copyStdKeysFilesIfNecessary()//from  w  ww .java  2 s .  c  om
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);

    // Show App version and footer.
    TextView tv = (TextView) findViewById(R.id.textViewMainFooter);
    tv.setText(getString(R.string.app_version) + ": " + Common.getVersionCode());

    // Add the context menu to the tools button.
    Button tools = (Button) findViewById(R.id.buttonMainTools);
    registerForContextMenu(tools);

    // Bind main layout buttons.
    mReadTag = (Button) findViewById(R.id.buttonMainReadTag);
    mWriteTag = (Button) findViewById(R.id.buttonMainWriteTag);
    mKeyEditor = (Button) findViewById(R.id.buttonMainEditKeyDump);
    mDumpEditor = (Button) findViewById(R.id.buttonMainEditCardDump);

    // Check if the user granted the app write permissions.
    if (Common.hasWritePermissionToExternalStorage(this)) {
        initFolders();
    } else {
        enableMenuButtons(false);
        // Request the permission.
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                REQUEST_WRITE_STORAGE_CODE);
    }

    // Check if there is an NFC hardware component.
    Common.setNfcAdapter(NfcAdapter.getDefaultAdapter(this));
    if (Common.getNfcAdapter() == null) {
        createNfcEnableDialog();
        mEnableNfc.show();
        mReadTag.setEnabled(false);
        mWriteTag.setEnabled(false);
        mResume = false;
    }

    // Show first usage notice.
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    final Editor sharedEditor = sharedPref.edit();
    boolean isFirstRun = sharedPref.getBoolean("is_first_run", true);
    if (isFirstRun) {
        new AlertDialog.Builder(this).setTitle(R.string.dialog_first_run_title)
                .setIcon(android.R.drawable.ic_dialog_alert).setMessage(R.string.dialog_first_run)
                .setPositiveButton(R.string.action_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (Common.IS_DONATE_VERSION) {
                            mResume = true;
                            checkNfc();
                        }
                        sharedEditor.putBoolean("is_first_run", false);
                        sharedEditor.apply();
                    }
                }).show();
        mResume = false;
    }

    if (Common.IS_DONATE_VERSION) {
        // Do not show the donate dialog.
        return;
    }
    // Show donate dialog.
    int currentVersion = 0;
    try {
        currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
    } catch (NameNotFoundException e) {
        Log.d(LOG_TAG, "Version not found.");
    }
    int lastVersion = sharedPref.getInt("mct_version", currentVersion - 1);
    boolean showDonateDialog = sharedPref.getBoolean("show_donate_dialog", true);
    if (lastVersion < currentVersion || showDonateDialog) {
        // This is either a new version of MCT or the user wants to see
        // the donate dialog.
        if (lastVersion < currentVersion) {
            // Update the version.
            sharedEditor.putInt("mct_version", currentVersion);
            sharedEditor.putBoolean("show_donate_dialog", true);
            sharedEditor.apply();
        }
        View dialogLayout = getLayoutInflater().inflate(R.layout.dialog_donate,
                (ViewGroup) findViewById(android.R.id.content), false);
        final CheckBox showDonateDialogCheckBox = (CheckBox) dialogLayout
                .findViewById(R.id.checkBoxDonateDialog);
        new AlertDialog.Builder(this).setTitle(R.string.dialog_donate_title)
                .setIcon(android.R.drawable.ic_dialog_info).setView(dialogLayout)
                .setPositiveButton(R.string.action_beer_sounds_fine, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Open Google Play for the donate version of MCT.
                        Uri uri = Uri.parse("market://details?id=de." + "syss.MifareClassicToolDonate");
                        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                        try {
                            startActivity(goToMarket);
                        } catch (ActivityNotFoundException e) {
                            startActivity(
                                    new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store"
                                            + "/apps/details?id=de.syss.Mifare" + "ClassicToolDonate")));
                        }
                        if (showDonateDialogCheckBox.isChecked()) {
                            // Do not show the donate dialog again.
                            sharedEditor.putBoolean("show_donate_dialog", false);
                            sharedEditor.apply();
                        }
                        mResume = true;
                        checkNfc();
                    }
                }).setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (showDonateDialogCheckBox.isChecked()) {
                            // Do not show the donate dialog again.
                            sharedEditor.putBoolean("show_donate_dialog", false);
                            sharedEditor.apply();
                        }
                        mResume = true;
                        checkNfc();
                    }
                }).show();
        mResume = false;
    }

    // Check if there is MIFARE Classic support.
    if (!Common.useAsEditorOnly() && !Common.hasMifareClassicSupport()) {
        // Disable read/write tag options.
        mReadTag.setEnabled(false);
        mWriteTag.setEnabled(false);
        CharSequence styledText = Html.fromHtml(getString(R.string.dialog_no_mfc_support_device));
        AlertDialog ad = new AlertDialog.Builder(this).setTitle(R.string.dialog_no_mfc_support_device_title)
                .setMessage(styledText).setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton(R.string.action_exit_app, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setNegativeButton(R.string.action_continue, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        mResume = true;
                        checkNfc();
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        finish();
                    }
                }).show();
        // Make links clickable.
        ((TextView) ad.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
        mResume = false;
    }
}

From source file:io.atrac613.AbstractNfcTagFragment.java

@Override
public void onPause() {
    Log.d(TAG, "*** AbstractNfcFeliCaTagFragment go Pause");
    if (this.getActivity().isFinishing()) {
        Log.d(TAG, "*** AbstractNfcFeliCaTagFragment will finishing");
        NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this.getActivity());
        adapter.disableForegroundDispatch(this.getActivity());
        sTechList = null;/*from   w ww  .j a  v  a  2s  . c o m*/
    }
    super.onPause();
}

From source file:de.syss.MifareClassicTool.Activities.MainMenu.java

/**
 * Check for NFC hardware, Mifare Classic support and for external storage.
 * If the directory structure and the std. keys files is not already there
 * it will be created. Also, at the first run of this App, a warning
 * notice and a donate message will be displayed.
 * @see #copyStdKeysFilesIfNecessary()/*from  ww  w .  ja  v a2s .  c om*/
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);

    // Show App version and footer.
    TextView tv = (TextView) findViewById(R.id.textViewMainFooter);
    tv.setText(getString(R.string.app_version) + ": " + Common.getVersionCode());

    // Add the context menu to the tools button.
    Button tools = (Button) findViewById(R.id.buttonMainTools);
    registerForContextMenu(tools);

    // Bind main layout buttons.
    mReadTag = (Button) findViewById(R.id.buttonMainReadTag);
    mWriteTag = (Button) findViewById(R.id.buttonMainWriteTag);
    mKeyEditor = (Button) findViewById(R.id.buttonMainEditKeyDump);
    mDumpEditor = (Button) findViewById(R.id.buttonMainEditCardDump);

    // Check if the user granted the app write permissions.
    if (Common.hasWritePermissionToExternalStorage(this)) {
        initFolders();
    } else {
        enableMenuButtons(false);
        // Request the permission.
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                REQUEST_WRITE_STORAGE_CODE);
    }

    // Check if there is an NFC hardware component.
    Common.setNfcAdapter(NfcAdapter.getDefaultAdapter(this));
    if (Common.getNfcAdapter() == null) {
        createNfcEnableDialog();
        mEnableNfc.show();
        mReadTag.setEnabled(false);
        mWriteTag.setEnabled(false);
        mResume = false;
    }

    // Show first usage notice.
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    final Editor sharedEditor = sharedPref.edit();
    boolean isFirstRun = sharedPref.getBoolean("is_first_run", true);
    if (isFirstRun) {
        new AlertDialog.Builder(this).setTitle(R.string.dialog_first_run_title)
                .setIcon(android.R.drawable.ic_dialog_alert).setMessage(R.string.dialog_first_run)
                .setPositiveButton(R.string.action_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (Common.IS_DONATE_VERSION) {
                            mResume = true;
                            checkNfc();
                        }
                        sharedEditor.putBoolean("is_first_run", false);
                        sharedEditor.apply();
                    }
                }).show();
        mResume = false;
    }

    if (Common.IS_DONATE_VERSION) {
        // Do not show the donate dialog.
        return;
    }
    // Show donate dialog.
    int currentVersion = 0;
    try {
        currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
    } catch (NameNotFoundException e) {
        Log.d(LOG_TAG, "Version not found.");
    }
    int lastVersion = sharedPref.getInt("mct_version", currentVersion - 1);
    boolean showDonateDialog = sharedPref.getBoolean("show_donate_dialog", true);
    if (lastVersion < currentVersion || showDonateDialog) {
        // This is either a new version of MCT or the user wants to see
        // the donate dialog.
        if (lastVersion < currentVersion) {
            // Update the version.
            sharedEditor.putInt("mct_version", currentVersion);
            sharedEditor.putBoolean("show_donate_dialog", true);
            sharedEditor.apply();
        }
        View dialogLayout = getLayoutInflater().inflate(R.layout.dialog_donate,
                (ViewGroup) findViewById(android.R.id.content), false);
        final CheckBox showDonateDialogCheckBox = (CheckBox) dialogLayout
                .findViewById(R.id.checkBoxDonateDialog);
        new AlertDialog.Builder(this).setTitle(R.string.dialog_donate_title)
                .setIcon(android.R.drawable.ic_dialog_info).setView(dialogLayout)
                .setPositiveButton(R.string.action_beer_sounds_fine, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Open Google Play for the donate version of MCT.
                        Uri uri = Uri.parse("market://details?id=de." + "syss.MifareClassicToolDonate");
                        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                        try {
                            startActivity(goToMarket);
                        } catch (ActivityNotFoundException e) {
                            startActivity(
                                    new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store"
                                            + "/apps/details?id=de.syss.Mifare" + "ClassicToolDonate")));
                        }
                        if (showDonateDialogCheckBox.isChecked()) {
                            // Do not show the donate dialog again.
                            sharedEditor.putBoolean("show_donate_dialog", false);
                            sharedEditor.apply();
                        }
                        mResume = true;
                        checkNfc();
                    }
                }).setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (showDonateDialogCheckBox.isChecked()) {
                            // Do not show the donate dialog again.
                            sharedEditor.putBoolean("show_donate_dialog", false);
                            sharedEditor.apply();
                        }
                        mResume = true;
                        checkNfc();
                    }
                }).show();
        mResume = false;
    }

    // Check if there is Mifare Classic support.
    if (!Common.useAsEditorOnly() && !Common.hasMifareClassicSupport()) {
        // Disable read/write tag options.
        mReadTag.setEnabled(false);
        mWriteTag.setEnabled(false);
        CharSequence styledText = Html.fromHtml(getString(R.string.dialog_no_mfc_support_device));
        AlertDialog ad = new AlertDialog.Builder(this).setTitle(R.string.dialog_no_mfc_support_device_title)
                .setMessage(styledText).setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton(R.string.action_exit_app, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setNegativeButton(R.string.action_continue, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        mResume = true;
                        checkNfc();
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        finish();
                    }
                }).show();
        // Make links clickable.
        ((TextView) ad.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
        mResume = false;
    }
}

From source file:com.golfwallet.main.MainActivity.java

/**   
 *  \brief/*from  w w w .ja  v  a2s  .  co  m*/
 *    Method called when the activity is created
 *    \param savedInstanceState Bundle used to pass information from previous activity to this one
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    MainActivity.context = getApplicationContext();

    isoDepAdapter = new IsoDepAdapter(getLayoutInflater());
    nfcAdapter = NfcAdapter.getDefaultAdapter(this);

    String username = ReadWriteData.read(context, ReadWriteData.LOGIN_USERNAME);
    String password = ReadWriteData.read(context, ReadWriteData.LOGIN_PASSWORD);

    if (ReadWriteData.getConnectionState(context) && username != null && password != null) {

        setContentView(R.layout.fragment_main);
        titleTextView = (TextView) findViewById(R.id.title);
        balanceTextView = (TextView) findViewById(R.id.balance);
        statusTextView = (TextView) findViewById(R.id.accountStatus);
        dateTextView = (TextView) findViewById(R.id.registrationDate);
        transactionListView = (ListView) findViewById(R.id.transactionList);

        // GET NEW TOKEN
        String token = null;
        try {
            token = new HTTPRequest().execute("/api/token", username, password).get();

            if (token != null) {
                ReadWriteData.write(context, ReadWriteData.LOGIN_TOKEN, token);
                saveAID();
            } else {
                Toast.makeText(MainActivity.this, "Connection issues, retry to connect.", Toast.LENGTH_SHORT)
                        .show();
                setConnected(false);
            }

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "Connection issues, retry to connect.", Toast.LENGTH_SHORT)
                    .show();
            setConnected(false);
        }

        // GET ACTIVITY CONTENT FROM API : USER INFORMATIONS
        String result = "error";
        try {
            if (token == null) {
                result = new HTTPRequest().execute("/api/user", username, password).get();
            } else {
                result = new HTTPRequest().execute("/api/user", token, "").get();
            }

            try {
                JSONObject jsonObj = new JSONObject(result);
                JSONObject user = (JSONObject) jsonObj.get("user");

                if (user.has("name") && user.has("surname")) {
                    titleTextView
                            .setText("Hi, " + user.getString("name") + " " + user.getString("surname") + " !");
                } else {
                    titleTextView.setText("Hi, " + user.getString("username") + " !");
                }

                balanceTextView.setText("balance : " + user.getInt("balance") + " CHF");

                switch (user.getInt("statement")) {
                case Constants.STA_USER_ACTIVE:
                    statusTextView.setText("account status : active");
                    break;
                case Constants.STA_USER_DELETED:
                    statusTextView.setText("account status : deleted");
                    break;
                case Constants.STA_USER_INACTIVE:
                    statusTextView.setText("account status : inactive");
                    break;
                }
                dateTextView.setText(
                        "registration date : " + user.getString("registrationDate").replace(" GMT", ""));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        // GET ACTIVITY CONTENT FROM API : TRANSACTIONS FROM USER
        result = "error";
        try {
            if (token == null) {
                result = new HTTPRequest().execute("/api/transactions", username, password).get();
            } else {
                result = new HTTPRequest().execute("/api/transactions", token, "").get();
            }

            List<Transaction> transactionList = new ArrayList<Transaction>();
            try {
                JSONObject jsonObj = new JSONObject(result);
                JSONArray json = (JSONArray) jsonObj.get("transactions");

                Toast.makeText(MainActivity.getAppContext(), "Your " + json.length() + " last transactions",
                        Toast.LENGTH_LONG).show();

                for (int i = 0; i < json.length(); i++) {
                    JSONObject c = json.getJSONObject(i);
                    int amount = c.getInt("amount");
                    int type = c.getInt("transactionType");
                    String transactionDate = c.getString("transactionDate");
                    String deviceId = c.getString("deviceId");
                    String dispenserId = c.getString("dispenserId");

                    transactionList.add(new Transaction(amount, type, transactionDate, deviceId, dispenserId));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            TransactionAdapter transactionAdapter = new TransactionAdapter(this, R.layout.transaction_row,
                    transactionList);

            transactionListView.setAdapter(transactionAdapter);

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    } else {
        setContentView(R.layout.log_layout);
        loginButton = (Button) findViewById(R.id.loginbutton);
        signinButton = (Button) findViewById(R.id.signinbutton);

        loginButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(loginIntent);
                finish();
            }
        });

        signinButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent signinIntent = new Intent(MainActivity.this, SigninActivity.class);
                startActivity(signinIntent);
                finish();
            }
        });
    }
}

From source file:com.mario22gmail.license.nfc_project.NavigationDrawerActivity.java

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

    NavigationDrawerActivity.context = getApplicationContext();

    setContentView(R.layout.navigation_drawer);

    nfcAdapter = NfcAdapter.getDefaultAdapter(this);

    //inregistrez contextul si filtru

    //set the main fragment
    //        FragmentStartPage mainFragment = new FragmentStartPage();
    //        ChangeFragment(mainFragment);

    //        FragmentEmptyState emptyFragment = new FragmentEmptyState();
    //        ChangeFragment(emptyFragment);
    AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
    AndroidAuthSession session = new AndroidAuthSession(appKeys);
    mDBApi = new DropboxAPI<AndroidAuthSession>(session);

    libInstance = NxpNfcLib.getInstance();
    libInstance.registerActivity(this, "");

    try {//from   www.  jav a 2  s .  co m
        ks = KeyStoreFactory.getInstance().getSoftwareKeyStore();
        ks.formatKeyEntry(2, IKeyConstants.KeyType.KEYSTORE_KEY_TYPE_2K3DES);
        ks.setKey(2, (byte) 0, IKeyConstants.KeyType.KEYSTORE_KEY_TYPE_2K3DES, KEY_2KTDES);

        ks.formatKeyEntry(3, IKeyConstants.KeyType.KEYSTORE_KEY_TYPE_DES);
        ks.setKey(3, (byte) 0, IKeyConstants.KeyType.KEYSTORE_KEY_TYPE_DES, MY_KEY_2KTDES);

        toolbar = (Toolbar) findViewById(R.id.toolbarNavigationDrawer);
        setSupportActionBar(toolbar);
    } catch (SmartCardException e) {
        e.printStackTrace();
    }

    libInstance.loadKeyStore(ks);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    FloatingActionMenu fabMenu = (FloatingActionMenu) findViewById(R.id.menuFab);

    fabMenu.hideMenuButton(false);

    fabMenu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
        @Override
        public void onMenuToggle(boolean opened) {
            String text;
            if (opened) {

                text = "Menu opened";
            } else {
                text = "Menu closed";
            }
            Log.i(nfcDebugTag, text);

        }
    });

    //        fab.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                fab.setLabelColors(ContextCompat.getColor(activity, Color.GRAY),
    //                        fab.getColor()
    //                        fab.getColor(activity, R.color.cardview_dark_background));
    //                fab.setLabelTextColor(ContextCompat.getColor(activity, Color.BLACK));
    //            }
    //
    //        });

    //        fabMenu.hideMenuButton(false);
    //        fab.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View view) {
    //                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
    //                        .setAction("Action", null).show();
    //            }
    //        });

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    FragmentStartPage startPage = new FragmentStartPage();
    ChangeFragment(startPage);

    //        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    //        getSupportActionBar().setHomeButtonEnabled(false);
}