Java Code Examples for android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED

The following examples show how to use android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED . 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: WifiNetworkActivity.java    From WiFiKeyShare with GNU General Public License v3.0 6 votes vote down vote up
private void setupForegroundDispatch() {
    /* initialize the PendingIntent to start for the dispatch */
    nfcPendingIntent = PendingIntent.getActivity(
            this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    /* initialize the IntentFilters to override dispatching for */
    nfcIntentFilters = new IntentFilter[3];
    nfcIntentFilters[0] = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    nfcIntentFilters[0].addCategory(Intent.CATEGORY_DEFAULT);
    nfcIntentFilters[1] = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    nfcIntentFilters[1].addCategory(Intent.CATEGORY_DEFAULT);
    nfcIntentFilters[2] = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    nfcIntentFilters[2].addCategory(Intent.CATEGORY_DEFAULT);
    try {
        nfcIntentFilters[0].addDataType("*/*"); // Handle all MIME based dispatches.
    } catch (IntentFilter.MalformedMimeTypeException e) {
        Log.e(TAG, "setupForegroundDispatch: " + e.getMessage());
    }

    /* Initialize the tech lists used to perform matching for dispatching of the
     * ACTION_TECH_DISCOVERED intent */
    nfcTechLists = new String[][] {};
}
 
Example 2
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 3
Source File: ZannenNfcWriter.java    From effective_android_sample with Apache License 2.0 6 votes vote down vote up
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

    setContentView(R.layout.main);
    findViewById(R.id.write_tag).setOnClickListener(mTagWriter);

    // Handle all of our received NFC intents in this activity.
    mNfcPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    // Intent filters for reading a note from a tag or exchanging over p2p.
    IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    try {
        ndefDetected.addDataType("text/plain");
    } catch (MalformedMimeTypeException e) { }
    mNdefExchangeFilters = new IntentFilter[] { ndefDetected };

    // Intent filters for writing to a tag
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    mWriteTagFilters = new IntentFilter[] { tagDetected };
}
 
Example 4
Source File: NfcDetectorActivity.java    From effective_android_sample with Apache License 2.0 6 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);
       writeTagFilters = new IntentFilter[] {ndefDetected, tagDetected, techDetected};
       
       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 5
Source File: ActivityAddFriend.java    From ploggy with GNU General Public License v3.0 6 votes vote down vote up
private void setupForegroundDispatch() {
    NfcAdapter nfcAdapter = getNfcAdapter();
    if (nfcAdapter != null) {
        IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            intentFilter.addDataType(getNfcMimeType());
        } catch (IntentFilter.MalformedMimeTypeException e) {
            Log.addEntry(LOG_TAG, e.getMessage());
            return;
        }
        nfcAdapter.enableForegroundDispatch(
               this,
               PendingIntent.getActivity(
                       this,
                       0,
                       new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0),
               new IntentFilter[] {intentFilter},
               null);
    }
}
 
Example 6
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 7
Source File: BlogViewer.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // Get the NFC Adapter.
  NfcManager nfcManager = (NfcManager)getSystemService(Context.NFC_SERVICE);
  mNFCAdapter = nfcManager.getDefaultAdapter();

  // Create the Pending Intent.
  int flags = 0;
  Intent nfcIntent = new Intent(this, getClass());
  nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
  mNFCPendingIntent =
    PendingIntent.getActivity(this, NFC_REQUEST_CODE, nfcIntent, flags);

  // Create an Intent Filter limited to the URI or MIME type to
  // intercept TAG scans from.
  IntentFilter tagIntentFilter =
    new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
  tagIntentFilter.addDataScheme("http");
  tagIntentFilter.addDataAuthority("blog.radioactiveyak.com", null);
  mIntentFiltersArray = new IntentFilter[] { tagIntentFilter };

  // Create an array of technologies to handle.
  mTechListsArray = new String[][] {
    new String[] {
      NfcF.class.getName()
    }
  };

  // Process the Intent used to start the Activity/
  String action = getIntent().getAction();
  if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
    processIntent(getIntent());
}
 
Example 8
Source File: AppRunnerActivity.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
public void initializeNFC() {

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

            if (nfcSupported == false) {
                return;
            }

            // when is in foreground
            MLog.d(TAG, "starting NFC");
            mAdapter = NfcAdapter.getDefaultAdapter(this);

            // PedingIntent will be delivered to this activity
            mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

            // Setup an intent filter for all MIME based dispatches
            IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
            try {
                ndef.addDataType("*/*");
            } catch (IntentFilter.MalformedMimeTypeException e) {
                throw new RuntimeException("fail", e);
            }
            mFilters = new IntentFilter[]{ndef,};

            // Setup a tech list for all NfcF tags
            mTechLists = new String[][]{new String[]{NfcF.class.getName()}};
            nfcInit = true;
        }
    }
 
Example 9
Source File: MainActivity.java    From android-nfc-tag-read-write with MIT License 5 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    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[] nfcIntentFilter = new IntentFilter[]{techDetected,tagDetected,ndefDetected};

    PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    if(mNfcAdapter!= null)
        mNfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);

}
 
Example 10
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 11
Source File: NfcActivity.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * Initializes which intents and NfcTechnologies to filter for
 */
private void initFields() {
    pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    mIntentFilters = new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)};
    mTechLists = new String[][]{new String[]{Ndef.class.getName()},
            new String[]{NdefFormatable.class.getName()}};
}
 
Example 12
Source File: NFCHandler.java    From timelapse-sony with GNU General Public License v3.0 5 votes vote down vote up
public static IntentFilter[] getIntentFilterArray() {
    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    try {
        ndef.addDataType(SONY_MIME_TYPE);
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    return new IntentFilter[]{ndef};
}
 
Example 13
Source File: ForegroundDispatch.java    From codeexamples-android with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    setContentView(R.layout.foreground_dispatch);
    mText = (TextView) findViewById(R.id.text);
    mText.setText("Scan a tag");

    mAdapter = NfcAdapter.getDefaultAdapter(this);

    // Create a generic PendingIntent that will be deliver to this activity. The NFC stack
    // will fill in the intent with the details of the discovered tag before delivering to
    // this activity.
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    // Setup an intent filter for all MIME based dispatches
    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    try {
        ndef.addDataType("*/*");
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    mFilters = new IntentFilter[] {
            ndef,
    };

    // Setup a tech list for all NfcF tags
    mTechLists = new String[][] { new String[] { NfcF.class.getName() } };
}
 
Example 14
Source File: NfcUtil.java    From zap-android with MIT License 4 votes vote down vote up
public static IntentFilter[] IntentFilters() {
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    return new IntentFilter[]{techDetected, tagDetected, ndefDetected};
}
 
Example 15
Source File: MainActivity.java    From QuickLyric with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String action = intent.getAction();
    String extra = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (action != null) {
        switch (action) {
            case NfcAdapter.ACTION_NDEF_DISCOVERED:
                Lyrics receivedLyrics = getBeamedLyrics(intent);
                if (receivedLyrics != null)
                    updateLyricsFragment(0, 0, false, true, receivedLyrics);
                break;
            case "android.intent.action.SEARCH":
                search(intent.getStringExtra(SearchManager.QUERY));
                break;
            case "android.intent.action.SEND":
                LyricsViewFragment lyricsViewFragment = (LyricsViewFragment) getFragmentManager()
                        .findFragmentByTag(LYRICS_FRAGMENT_TAG);
                new IdDecoder(this, lyricsViewFragment).execute(getIdUrl(extra));
                selectItem(0);
                break;
            case "android.intent.action.VIEW":
                if (intent.getDataString().contains("spotify"))
                    Spotify.onCallback(intent, this);
                break;
            case "com.geecko.QuickLyric.getLyrics":
                String[] metadata = intent.getStringArrayExtra("TAGS");
                if (metadata != null) {
                    String artist = metadata[0];
                    String track = metadata[1];
                    LyricsViewFragment lyricsFragment = (LyricsViewFragment) getFragmentManager()
                            .findFragmentByTag(LYRICS_FRAGMENT_TAG);
                    lyricsFragment.fetchLyrics(true, null, 0L, artist, track);
                    lyricsFragment.manualUpdateLock = true;
                    selectItem(0);
                }
                break;
            case "com.geecko.QuickLyric.updateDBList":
                updateDBList();
                break;
        }
    }
}
 
Example 16
Source File: NfcActivity.java    From commcare-android with Apache License 2.0 3 votes vote down vote up
/**
 * Makes it so that this activity will be the default to handle a new tag when it is discovered.
 *
 * The intent filters being passed to enableForegroundDispatch() here are intentionally very
 * broad, on the assumption that if CommCare's NfcActivity is in the foreground while a user
 * tries to scan an NFC tag, they were intending to scan something that CommCare would
 * recognize. So if the user scans a tag of a type that we aren't expecting, instead of
 * filtering it out (which would result in the device's default NFC handler consuming the tag,
 * resulting in confusing on-screen behavior for the user), we'll consume it ourselves and
 * then show a useful error message.
 */
private void setReadyToHandleTag() {
    IntentFilter ndefDiscoveredFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    IntentFilter tagDiscoveredFilter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    IntentFilter[] intentFilters = new IntentFilter[]{ndefDiscoveredFilter, tagDiscoveredFilter};
    this.nfcManager.enableForegroundDispatch(this, this.pendingNfcIntent, intentFilters, null);
}