Example usage for android.content IntentFilter addDataType

List of usage examples for android.content IntentFilter addDataType

Introduction

In this page you can find the example usage for android.content IntentFilter addDataType.

Prototype

public final void addDataType(String type) throws MalformedMimeTypeException 

Source Link

Document

Add a new Intent data type to match against.

Usage

From source file:it.imwatch.nfclottery.MainActivity.java

/**
 * Sets up the dispatching of NFC events a the foreground Activity.
 *
 * @param activity The {@link android.app.Activity} to setup the foreground dispatch for
 * @param adapter  The {@link android.nfc.NfcAdapter} to setup the foreground dispatch for
 *///from   w  w  w  .j  a  v  a2s .c om
public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
    if (adapter != null) {
        final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0,
                intent, 0);
        IntentFilter[] filters = new IntentFilter[1];
        String[][] techList = new String[][] {};

        // Notice that this is the same filter we define in our manifest.
        // This ensures we're not stealing events for other types of NDEF.
        filters[0] = new IntentFilter();
        IntentFilter filter = filters[0];
        filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        try {
            filter.addDataType(MIME_VCARD);
            filter.addDataType(MIME_XVCARD);
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("Mime type not supported.");
        }

        adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
    }
}

From source file:Main.java

private static final boolean initIntentFilterFromXml(IntentFilter inf, XmlPullParser xpp) {
    try {/*  ww  w .  j ava  2  s  .  co m*/
        int outerDepth = xpp.getDepth();
        int type;
        final String NAME = "name";
        while ((type = xpp.next()) != XmlPullParser.END_DOCUMENT
                && (type != XmlPullParser.END_TAG || xpp.getDepth() > outerDepth)) {
            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT)
                continue;
            String tag = xpp.getName();
            if (tag.equals("action")) {
                String name = xpp.getAttributeValue(null, NAME);
                if (name != null)
                    inf.addAction(name);
            } else if (tag.equals("category")) {
                String name = xpp.getAttributeValue(null, NAME);
                if (name != null)
                    inf.addCategory(name);
            } else if (tag.equals("data")) {
                int na = xpp.getAttributeCount();
                for (int i = 0; i < na; i++) {
                    String port = null;
                    String an = xpp.getAttributeName(i);
                    String av = xpp.getAttributeValue(i);
                    if ("mimeType".equals(an)) {
                        try {
                            inf.addDataType(av);
                        } catch (MalformedMimeTypeException e) {
                        }
                    } else if ("scheme".equals(an)) {
                        inf.addDataScheme(av);
                    } else if ("host".equals(an)) {
                        inf.addDataAuthority(av, port);
                    } else if ("port".equals(an)) {
                        port = av;
                    } else if ("path".equals(an)) {
                        inf.addDataPath(av, PatternMatcher.PATTERN_LITERAL);
                    } else if ("pathPrefix".equals(an)) {
                        inf.addDataPath(av, PatternMatcher.PATTERN_PREFIX);
                    } else if ("pathPattern".equals(an)) {
                        inf.addDataPath(av, PatternMatcher.PATTERN_SIMPLE_GLOB);
                    }
                }
            }
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

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

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

    BugSenseHandler.initAndStartSession(WriteNFCActivity.this, "44a76a8c");

    setContentView(R.layout.write_tag_activity);

    try {/*from w  w w.  j a  v  a  2 s  .  c  om*/
        getActionBar().setSubtitle(getString(R.string.NFCTitle));
        getActionBar().setDisplayHomeAsUpEnabled(true);
    } catch (Exception gab) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", gab);
    }

    //Quick test
    try {
        UID = getIntent().getExtras().getString(PAYLOAD_UID).replace("/zport/dmd/Devices/", "");

        aaRecord = NdefRecord.createApplicationRecord("net.networksaremadeofstring.rhybudd");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            //idRecord = NdefRecord.createExternal("rhybudd:tag", "z", UID.getBytes(Charset.forName("US-ASCII")));
            idRecord = NdefRecord.createMime("application/vnd.rhybudd.device", UID.getBytes());
        } else {
            idRecord = NdefRecord.createUri("rhybudd://" + UID);
        }

        ((TextView) findViewById(R.id.SizesText)).setText("This payload is "
                + (aaRecord.toByteArray().length + idRecord.toByteArray().length)
                + " bytes.\n\nAn ultralight can store up to 46 bytes.\nAn Ultralight C or NTAG203 can store up to 137 bytes.\nDespite the name a 1K can only store up to 716 bytes.");
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", e);
        try {
            Toast.makeText(this, "Sorry there was error parsing the passed UID, we cannot continue.",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception t) {
            BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", t);
        }

        finish();
    }

    try {
        mAdapter = NfcAdapter.getDefaultAdapter(this);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate getDefaultAdapter", e);
        mAdapter = null;
    }

    try {
        pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate pendingIntent", e);
    }

    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) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate", e);
        throw new RuntimeException("fail", e);
    }

    try {
        IntentFilter td = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        intentFiltersArray = new IntentFilter[] { ndef, td };

        techListsArray = new String[][] { new String[] { NfcF.class.getName(), NfcA.class.getName(),
                Ndef.class.getName(), NdefFormatable.class.getName() } };
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "onCreate IntentFilter", e);
    }

    CreateHandlers();
}

From source file:io.atrac613.AbstractNfcTagFragment.java

@Override
public void onResume() {
    Log.d(TAG, "*** AbstractNfcFeliCaTagFragment go Resume");

    //foregrandDispathch
    Activity a = this.getActivity();
    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    IntentFilter tag = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    try {//  w w w .  j av a  2s . com
        ndef.addDataType("*/*");
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    IntentFilter[] filters = new IntentFilter[] { ndef, tag, tech };

    PendingIntent pendingIntent = PendingIntent.getActivity(a, 0,
            new Intent(a, a.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this.getActivity());

    adapter.enableForegroundDispatch(this.getActivity(), pendingIntent, filters, registerTechList(mTechList));

    super.onResume();
}

From source file:mai.whack.StickyNotesActivity.java

/** Called when the activity is first created. */
@Override//from  ww  w. ja v a2  s .c o m
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 };
}

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

public void initializeNFC() {

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

        if (nfcSupported == false) {
            return;
        }//from   w w  w .  j  av a  2s . co  m

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

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

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

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

From source file:com.googlecode.android_scripting.facade.ui.NFCBeamTask.java

@SuppressLint("NewApi")
public void launchNFC() {
    Log.d(TAG, "launchNFC:" + beamStat);
    if (beamStat == 0) {
        _nfcAdapter.setNdefPushMessageCallback(this, getActivity());
        _nfcAdapter.setOnNdefPushCompleteCallback(this, getActivity());

        // start NFC Connection
        /*_nfcPendingIntent = PendingIntent.getActivity(getActivity().getApplicationContext(), 0,
              new Intent(getActivity().getApplicationContext(), FutureActivity.class)
             .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
                //  w ww .ja v a 2s .  c om
        IntentFilter ndefDetected = new IntentFilter(
              NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
           ndefDetected.addDataType("application/com.hipipal.qpy.nfc");
        } catch (MalformedMimeTypeException e) {
           throw new RuntimeException("Could not add MIME type.", e);
        }
                
        _readTagFilters = new IntentFilter[] { ndefDetected };*/
    } else if (beamStat == 1) {
        //_nfcAdapter.setNdefPushMessageCallback(this, getActivity());
        //_nfcAdapter.setOnNdefPushCompleteCallback(this, getActivity());

        // start NFC Connection
        _nfcPendingIntent = PendingIntent.getActivity(getActivity().getApplicationContext(), 0,
                new Intent(getActivity().getApplicationContext(), FutureActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                0);

        IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndefDetected.addDataType("application/com.hipipal.qpy.nfc");
        } catch (MalformedMimeTypeException e) {
            throw new RuntimeException("Could not add MIME type.", e);
        }

        _readTagFilters = new IntentFilter[] { ndefDetected };
    }
}

From source file:net.lp.hivawareness.v4.HIVAwarenessActivity.java

/** Called when the activity is first created. */
@Override/*  w  ww.  j a va 2  s  .c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);

    //Save ApplicationContext
    applicationContext = this.getApplicationContext();

    enableStrictMode();

    if (DEBUG && mStrictModeAvailable) {
        StrictModeWrapper.allowThreadDiskWrites();//disables temporarily, reenables below
    }

    if (!DEBUG) {
        //BugSense uncaught exceptions analytics.
        BugSenseHandler.setup(this, BUGSENSE_API_KEY);
    }

    //Enable analytics session. Should be first (at least before any Flurry calls).
    if (!HIVAwarenessActivity.DEBUG)
        FlurryAgent.onStartSession(this, HIVAwarenessActivity.FLURRY_API_KEY);

    if (mBackupManagerAvailable) {
        mBackupManagerWrapper = new BackupManagerWrapper(this);//TODO: should this be app context?
        Log.i(TAG, "BackupManager API available.");
    } else {
        Log.i(TAG, "BackupManager API not available.");
    }

    //Load the default preferences values. Should be done first at every entry into the app.
    PreferenceManager.setDefaultValues(HIVAwarenessActivity.getAppCtxt(), PREFS, MODE_PRIVATE,
            R.xml.preferences, false);
    HIVAwarenessActivity.dataChanged();

    //Obtain a connection to the preferences.
    SharedPreferences prefs = getSharedPreferences(PREFS, MODE_PRIVATE);

    mGender = Gender.valueOf(prefs.getString(PREFS_GENDER, "male"));

    String region = prefs.getString(PREFS_REGION, null);
    if (region == null) {
        mRegion = null;
    }
    caught = prefs.getInt(PREFS_INFECTED, -1);

    if (caught == -1) {
        calculateInitial(mRegion == null);
    } else {

    }

    // Check for available NFC Adapter
    mNfcAdapter = NfcAdapter.getDefaultAdapter(HIVAwarenessActivity.getAppCtxt());
    if (mNfcAdapter == null) {
        Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
        if (!DEBUG)
            finish();
    }
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    try {
        ndef.addDataType("application/net.lp.hivawareness.beam");
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    mIntentFiltersArray = new IntentFilter[] { ndef };
    mTechListsArray = new String[][] { new String[] { NfcF.class.getName() } };
}

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

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

From source file:edu.cmu.mpcs.dashboard.TagViewer.java

private void enableTagWriteMode() {
    Log.d("TAG_VIEWER", "in enable tag write");
    mWriteMode = true;//from  w ww  .  j  a  v a  2 s  .  c o m
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    // tagDetected.addDataScheme("http");
    // IntentFilter techFilter = new
    // IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    try {
        tagDetected.addDataType("text/plain");
        // tagDetected.addDataScheme("http");
        // techFilter.addDataType("text/plain");
    } catch (MalformedMimeTypeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    IntentFilter httpDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    httpDetected.addDataScheme("http");

    mWriteTagFilters = new IntentFilter[] { tagDetected, httpDetected };
    mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, null);
}