Java Code Examples for android.nfc.NfcAdapter#getDefaultAdapter()

The following examples show how to use android.nfc.NfcAdapter#getDefaultAdapter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConnectivityServiceWrapper.java    From GravityBox with Apache License 2.0 6 votes vote down vote up
private static void sendNfcState(ResultReceiver receiver) {
    if (mContext == null || receiver == null) return;
    int nfcState = NFC_STATE_UNKNOWN;
    try {
        NfcAdapter adapter = NfcAdapter.getDefaultAdapter(mContext);
        if (adapter != null) {
            nfcState = (Integer) XposedHelpers.callMethod(adapter, "getAdapterState");
        }
    } catch (Throwable t) {
        XposedBridge.log(t);
    } finally {
        Bundle b = new Bundle();
        b.putInt("nfcState", nfcState);
        receiver.send(0, b);
    }
}
 
Example 2
Source File: NfcDetectorActivity.java    From external-nfc-api with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
	Log.d(TAG, "onCreate");

	nxpMifareClassic = hasMifareClassic();
	 
	// Check for available NFC Adapter
	PackageManager pm = getPackageManager();
	if(pm.hasSystemFeature(PackageManager.FEATURE_NFC) && NfcAdapter.getDefaultAdapter(this) != null) {
    	Log.d(TAG, "NFC feature found");

		onNfcFeatureFound();
	} else {
    	Log.d(TAG, "NFC feature not found");

		onNfcFeatureNotFound();
	}
	
}
 
Example 3
Source File: BeamLargeFilesFragment.java    From connectivity-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Standard lifecycle event. Registers a callback for large-file transfer, by calling
 * NfcAdapter.setBeamPushUrisCallback().
 *
 * Note: Like sending NDEF messages over standard Android Beam, there is also a non-callback
 * API available. See: NfcAdapter.setBeamPushUris().
 *
 * @param savedInstanceState Saved instance state.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    Activity a = getActivity();

    // Setup Beam to transfer a large file. Note the call to setBeamPushUrisCallback().
    // BEGIN_INCLUDE(setBeamPushUrisCallback)
    NfcAdapter nfc = NfcAdapter.getDefaultAdapter(a);
    if (nfc != null) {
        Log.w(TAG, "NFC available. Setting Beam Push URI callback");
        nfc.setBeamPushUrisCallback(this, a);
    } else {
        Log.w(TAG, "NFC is not available");
    }
    // END_INCLUDE(setBeamPushUrisCallback)
}
 
Example 4
Source File: MainActivity.java    From QuickLyric with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    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) {
        }
    }
    updatePrefsChanges();
    AppBarLayout appBarLayout = findViewById(id.appbar);
    appBarLayout.removeOnOffsetChangedListener(this);
    appBarLayout.addOnOffsetChangedListener(this);
}
 
Example 5
Source File: MainActivity.java    From QuickLyric with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onPause() {
    super.onPause();
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (nfcAdapter != null)
        nfcAdapter.disableForegroundDispatch(this);
    AppBarLayout appBarLayout = findViewById(id.appbar);
    appBarLayout.removeOnOffsetChangedListener(this);
}
 
Example 6
Source File: NFCTagPreferenceX.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
void writeToNFCTag(long id, String tag) {

        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(prefContext);
        if (!nfcAdapter.isEnabled()) {
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(prefContext);
            dialogBuilder.setTitle(R.string.nfc_tag_pref_dlg_menu_writeToNfcTag);
            dialogBuilder.setMessage(R.string.nfc_tag_pref_dlg_writeToNfcTag_nfcNotEnabled);
            dialogBuilder.setPositiveButton(android.R.string.ok, null);
            AlertDialog dialog = dialogBuilder.create();

//            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
//                @Override
//                public void onShow(DialogInterface dialog) {
//                    Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);
//                    if (positive != null) positive.setAllCaps(false);
//                    Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);
//                    if (negative != null) negative.setAllCaps(false);
//                }
//            });

            if (fragment.getActivity() != null)
                if (!fragment.getActivity().isFinishing())
                    dialog.show();
            return;
        }

        Intent nfcTagIntent = new Intent(prefContext.getApplicationContext(), NFCTagWriteActivity.class);
        nfcTagIntent.putExtra(NFCTagWriteActivity.EXTRA_TAG_NAME, tag);
        nfcTagIntent.putExtra(NFCTagWriteActivity.EXTRA_TAG_DB_ID, id);
        ((Activity) prefContext).startActivityForResult(nfcTagIntent, RESULT_NFC_TAG_WRITE);
    }
 
Example 7
Source File: TagDispatcher.java    From nordpol with MIT License 5 votes vote down vote up
/**
 * Disable exclusive NFC access for the given activity.
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public void disableExclusiveNfc() {
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity);
    if (adapter != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            disableReaderMode(adapter);
        } else {
            disableForegroundDispatch(adapter);
        }
    }
}
 
Example 8
Source File: PayActivity.java    From HandstandPay with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.set_as_default) {
        DefaultPaymentAppUtil.ensureSetAsDefaultPaymentApp(PayActivity.this);
        return true;
    } else if (id == R.id.play_animation) {
        LocalBroadcastManager.getInstance(PayActivity.this).sendBroadcast(new Intent(HandstandApduService.PAYMENT_SENT));
        return true;
    } else if (id == R.id.edit_magstripe) {
        startEditMagstripeActivity();
        return true;
    } else if (id == R.id.nfc_settings) {
        NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(PayActivity.this);

        //Tell the user whether NFC is enabled
        String message = "NFC is enabled: " + mNfcAdapter.isEnabled();
        Toast.makeText(PayActivity.this, message, Toast.LENGTH_SHORT).show();

        //Show the settings regardless of whether it is enabled or not
        Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
        startActivity(intent);
    }

    return super.onOptionsItemSelected(item);
}
 
Example 9
Source File: NfcDetectorActivity.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
/**
    * 
    * Initialize Nfc fields
    * 
    */
   
protected void initializeNfc() {
	nfcAdapter = NfcAdapter.getDefaultAdapter(this);
	nfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	
       IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
       IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
       IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
       IntentFilter tagLost = new IntentFilter(ACTION_TAG_LEFT_FIELD);
       
       writeTagFilters = new IntentFilter[] {ndefDetected, tagDetected, techDetected, tagLost};
       
       nfcStateChangeBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final int state = intent.getIntExtra(EXTRA_ADAPTER_STATE, -1);
			if(state == STATE_OFF || state == STATE_ON) {
				
				runOnUiThread(new Runnable() {
				    public void run() {
						if(state == STATE_ON) {
							if(detecting) {
								enableForeground();
							}
						} 

				    	detectNfcStateChanges();
				    }
				});
			}
		}
	};
}
 
Example 10
Source File: HostConnectionProfile.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public boolean onRequest(final Intent request, final Intent response) {
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(getContext());
    if (adapter != null) {
        if (adapter.isEnabled()) {
            response.putExtra(PARAM_ENABLE, true);
        } else {
            response.putExtra(PARAM_ENABLE, false);
        }
    } else {
        response.putExtra(PARAM_ENABLE, false);
    }
    setResult(response, IntentDConnectMessage.RESULT_OK);
    return true;
}
 
Example 11
Source File: TagDispatcher.java    From WalletCordova with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** Disable exclusive NFC access for the given activity.
 * @returns true if NFC was available and false if no NFC is available
 *          on device.
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public boolean disableExclusiveNfc() {
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity);
    if (adapter != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            disableReaderMode(adapter);
        } else {
            disableForegroundDispatch(adapter);
        }
        return true;
    }
    return false;
}
 
Example 12
Source File: NfcDataWriteActivity.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void init() {
    Intent nfcIntent = new Intent(this, this.getClass());
    nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0);
    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    try {
        ndef.addDataType("*/*");    /* Handles all MIME based dispatches.
                                   You should specify only the ones that you need. */
    } catch (IntentFilter.MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    IntentFilter[] intentFiltersArray = new IntentFilter[]{ndef,};
    String[][] techList = new String[1][1];
    techList[0][0] = MifareClassic.class.getName();
    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techList);
    disposable.add(
            nfcManager.requestProgressProcessor().onBackpressureBuffer()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                            message -> binding.currentMessage.setText(message),
                            Timber::e
                    )
    );

    disposable.add(
            nfcManager.requestInitProcessor()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(init -> {
                                if (!init) {
                                    binding.nfcBg.animate().scaleX(0.1f).scaleY(0.1f).setDuration(1500)
                                            .withEndAction(() -> binding.nfcBg.setVisibility(View.GONE));
                                }
                            },
                            Timber::e)
    );
}
 
Example 13
Source File: NfcDeviceManager.java    From yubikit-android with Apache License 2.0 5 votes vote down vote up
/**
 * Creates instance of {@link NfcDeviceManager}
 * @param context the application context
 * @param dispatcher optional implementation of NfcDispatcher to use instead of the default.
 */
public NfcDeviceManager(Context context, NfcDispatcher dispatcher) {
    this.context = context;
    adapter = NfcAdapter.getDefaultAdapter(this.context);
    if (dispatcher == null) {
        dispatcher = new NfcReaderDispatcher(adapter);
    }
    this.dispatcher = dispatcher;
}
 
Example 14
Source File: ConnectionFragment.java    From timelapse-sony with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mApplication = (TimelapseApplication) getActivity().getApplication();

    mDeviceManager = mApplication.getDeviceManager();
    mStateMachineConnection = mApplication.getStateMachineConnection();

    mNfcAdapter = NfcAdapter.getDefaultAdapter(getContext());
}
 
Example 15
Source File: BeamController.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * If the device has NFC, construct a BeamCallback and pass it to Android.
 *
 * @param activity Activity that is sending out beam messages.
 * @param provider Provider that returns the URL that should be shared.
 */
public static void registerForBeam(final Activity activity, final BeamProvider provider) {
    final NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
    if (nfcAdapter == null) return;
    if (activity.checkPermission(Manifest.permission.NFC, Process.myPid(), Process.myUid())
            == PackageManager.PERMISSION_DENIED) return;
    try {
        final BeamCallback beamCallback = new BeamCallback(activity, provider);
        nfcAdapter.setNdefPushMessageCallback(beamCallback, activity);
        nfcAdapter.setOnNdefPushCompleteCallback(beamCallback, activity);
    } catch (IllegalStateException e) {
        Log.w("BeamController", "NFC registration failure. Can't retry, giving up.");
    }
}
 
Example 16
Source File: NfcManager.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
public void checkForNFCSupport() throws NfcNotSupportedException, NfcNotEnabledException {
    this.nfcAdapter = NfcAdapter.getDefaultAdapter(this.context);
    if (nfcAdapter == null)
        throw new NfcNotSupportedException();
    if (!nfcAdapter.isEnabled())
        throw new NfcNotEnabledException();
}
 
Example 17
Source File: NfcDeviceFragment.java    From ESeal with Apache License 2.0 4 votes vote down vote up
private void disableNfcReaderMode() {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
    if (nfcAdapter != null) {
        nfcAdapter.disableReaderMode(getActivity());
    }
}
 
Example 18
Source File: PGPClipperResultShowActivity.java    From PGPClipper with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String currentTheme = sharedPreferences.getString("themeSelection", "dark");

    switch (currentTheme) {
        case "dark":
            setTheme(R.style.PseudoDialogDarkTheme);
            break;
        case "light":
            setTheme(R.style.PseudoDialogLightTheme);
            break;
    }

    super.onCreate(savedInstanceState);

    intent = getIntent();

    setContentView(R.layout.resultactivitylayout);

    sigStatus = findViewById(R.id.sigStatusTitle);
    decStatus = findViewById(R.id.decryptionStatusTitle);
    decResult = findViewById(R.id.decryptionResultText);
    underTextIndicator = findViewById(R.id.underTextIndicator);

    preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    adapter = NfcAdapter.getDefaultAdapter(this);

    sigStatus.setText(getString(R.string.signatureStatusText, "", ""));
    decStatus.setText(getString(R.string.decryptionStatusText, ""));

    String currentPgpProvider = preferences.getString("pgpServiceProviderApp", null);

    if (currentPgpProvider == null || "".equals(currentPgpProvider)) {
        // Default security provider is not set
        Log.e("PGPClipperService", "Security provider is not set!");
    } else {
        Log.d("PGPClipperService", "Current security provider: " + currentPgpProvider);

        serviceConnection = new OpenPgpServiceConnection(this, currentPgpProvider);
        serviceConnection.bindToService();

        if (preferences.getBoolean("enableNFCAuth", false) && adapter.isEnabled()) {
            waitingNFC = true;
        }
        if (preferences.getBoolean("enableFingerprintAuth", false))
        {
            waitingFingerprint = true;
        }
        if (!preferences.getBoolean("enableNFCAuth", false) &&
                !preferences.getBoolean("enableFingerprintAuth", false)) {
            tryDecryption();
        }
        else
        {
            StringBuilder authenticationMethod = new StringBuilder();
            if (preferences.getBoolean("enableNFCAuth", false) &&
                    preferences.getBoolean("enableFingerprintAuth", false))
            {
                authenticationMethod.append(getString(R.string.alternativeAuthenticationMethodNFCText));
                authenticationMethod.append(" / ");
                authenticationMethod.append(getString(R.string.alternativeAuthenticationMethodFingerprintText));
            }
            else if (preferences.getBoolean("enableNFCAuth", false) &&
                    !preferences.getBoolean("enableFingerprintAuth", false))
            {
                authenticationMethod.append(getString(R.string.alternativeAuthenticationMethodNFCText));
            }
            else if (!preferences.getBoolean("enableNFCAuth", false) &&
                    preferences.getBoolean("enableFingerprintAuth", false))
            {
                authenticationMethod.append(getString(R.string.alternativeAuthenticationMethodFingerprintText));
            }

            underTextIndicator.setText(getString(R.string.alternativeAuthenticationMethodText, authenticationMethod.toString()));
        }

    }
}
 
Example 19
Source File: NFCAuthenticationSetupActivity.java    From PGPClipper with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    if ( Objects.requireNonNull(sharedPreferences.getString("themeSelection", "dark")).equals("dark") )
    {
        setTheme(R.style.AppThemeDark);
    }
    else
    {
        setTheme(R.style.AppTheme);
    }

    super.onCreate(savedInstanceState);

    setContentView(R.layout.wizardlayout);

    parent = (RelativeLayout) findViewById(R.id.parent);
    screen = (RelativeLayout) findViewById(R.id.setupScreen);

    layoutInflater(stage);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    editor = sharedPreferences.edit();

    nfcAdapter = NfcAdapter.getDefaultAdapter(this);

    if (nfcAdapter == null) {
        Toast.makeText(this, R.string.nfcNotAvailableString, Toast.LENGTH_LONG).show();
        setResult(RESULT_CANCELED);
        finish();
    }
    else if (!nfcAdapter.isEnabled()) {
        Toast.makeText(this, R.string.nfcDisabledString, Toast.LENGTH_LONG).show();
        startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
    }

    // just to be sure, initialize settings

    initSetting(editor);

    // make screen on always on this activity

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


}
 
Example 20
Source File: NfcHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Checks if NFC is supported by the device
 *
 * @param context any suitable context
 * @return true if NFC is supported, false otherwise
 */
public static boolean isNfcEnabled(Context context) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
    return nfcAdapter.isEnabled();
}