Example usage for android.content Intent getType

List of usage examples for android.content Intent getType

Introduction

In this page you can find the example usage for android.content Intent getType.

Prototype

public @Nullable String getType() 

Source Link

Document

Retrieve any explicit MIME type included in the intent.

Usage

From source file:info.papdt.blacklight.ui.statuses.NewPostActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    mLayout = R.layout.post_status;//from w  w  w . j  a  v a2s .  c  om
    super.onCreate(savedInstanceState);

    mLoginCache = new LoginApiCache(this);
    mUserCache = new UserApiCache(this);
    new GetAvatarTask().execute();

    // Initialize views
    mText = Utility.findViewById(this, R.id.post_edit);
    mCount = Utility.findViewById(this, R.id.post_count);
    mDrawer = Utility.findViewById(this, R.id.post_drawer);
    mAvatar = Utility.findViewById(this, R.id.post_avatar);
    mScroll = Utility.findViewById(this, R.id.post_scroll);
    mPicsParent = Utility.findViewById(this, R.id.post_pics);
    mPic = Utility.findViewById(this, R.id.post_pic);
    mEmoji = Utility.findViewById(this, R.id.post_emoji);
    mAt = Utility.findViewById(this, R.id.post_at);
    mTopic = Utility.findViewById(this, R.id.post_topic);
    mSend = Utility.findViewById(this, R.id.post_send);
    mCache = getSharedPreferences("post_cache", MODE_PRIVATE);

    // Bind onClick events
    Utility.bindOnClick(this, mPic, "pic");
    Utility.bindOnClick(this, mEmoji, "emoji");
    Utility.bindOnClick(this, mAt, "at");
    Utility.bindOnClick(this, mTopic, "topic");
    Utility.bindOnClick(this, mSend, "send");
    Utility.bindOnClick(this, mAvatar, "avatar");

    // Version
    try {
        mVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (Exception e) {
    }

    // Hints
    if (Math.random() < 0.42) { // Make this a matter of possibility.
        mHints = getResources().getStringArray(R.array.splashes);
        mText.setHint(mHints[new Random().nextInt(mHints.length)]);
    }

    // Fragments
    mEmoticonFragment = new EmoticonFragment();
    mColorPickerFragment = new ColorPickerFragment();
    getFragmentManager().beginTransaction().replace(R.id.post_emoticons, mEmoticonFragment).commit();

    // Filter
    try {
        TypedArray array = getTheme().obtainStyledAttributes(R.styleable.BlackLight);
        mFilter = array.getColor(R.styleable.BlackLight_NewPostImgFilter, 0);
        mForeground = array.getColor(R.styleable.BlackLight_NewPostForeground, 0);
        array.recycle();
    } catch (Exception e) {
        mFilter = 0;
    }

    // Listeners
    mEmoticonFragment.setEmoticonListener(new EmoticonFragment.EmoticonListener() {
        @Override
        public void onEmoticonSelected(String name) {
            mText.getText().insert(mText.getSelectionStart(), name);
            mDrawer.closeDrawer(Gravity.RIGHT);
        }
    });

    mColorPickerFragment.setOnColorSelectedListener(new ColorPickerFragment.OnColorSelectedListener() {
        @Override
        public void onSelected(String hex) {
            int sel = mText.getSelectionStart();
            mText.getText().insert(sel, "[" + hex + "  [d");
            mText.setSelection(sel + 9);
            mDrawer.closeDrawer(Gravity.RIGHT);
        }
    });

    mText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (needCache())
                mCache.edit().putString(DRAFT, s.toString()).apply();
        }

        @Override
        public void afterTextChanged(Editable s) {
            // How many Chinese characters (1 Chinses character = 2 English characters)
            try {
                int length = Utility.lengthOfString(s.toString());

                if (DEBUG) {
                    Log.d(TAG, "Text length = " + length);
                }

                if (length <= 140 && !s.toString().contains("\n")) {
                    mCount.setTextColor(mForeground);
                    mCount.setText(String.valueOf(140 - length));
                    mIsLong = false;
                } else if (!(NewPostActivity.this instanceof RepostActivity)
                        && !(NewPostActivity.this instanceof CommentOnActivity)
                        && !(NewPostActivity.this instanceof ReplyToActivity)) {
                    mCount.setText(getResources().getString(R.string.long_post));
                    mIsLong = true;
                } else {
                    mCount.setTextColor(getResources().getColor(android.R.color.holo_red_light));
                    mCount.setText(String.valueOf(140 - length));
                    mIsLong = false;
                }

            } catch (Exception e) {

            }

            if (mEmoji != null) {
                if (mIsLong) {
                    getFragmentManager().beginTransaction().replace(R.id.post_emoticons, mColorPickerFragment)
                            .commit();
                    mEmoji.setImageResource(R.drawable.ic_mode_edit_black_36dp);
                } else {
                    getFragmentManager().beginTransaction().replace(R.id.post_emoticons, mEmoticonFragment)
                            .commit();
                    mEmoji.setImageResource(R.drawable.ic_emoji);

                }
            }
        }
    });

    getWindow().getDecorView().getViewTreeObserver()
            .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    mText.requestFocus();
                    mText.requestFocusFromTouch();

                    // Draft
                    if (needCache())
                        mText.setText(mCache.getString(DRAFT, ""));

                    // Must be removed
                    getWindow().getDecorView().getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            });

    // Imgs
    for (int i = 0; i < 9; i++) {
        mPics[i] = (ImageView) mPicsParent.getChildAt(i);
        mPics[i].setOnLongClickListener(this);
        mPics[i].setOnClickListener(this);
    }

    // Handle share intent
    Intent i = getIntent();

    if (i != null && i.getType() != null) {
        if (i.getType().contains("text/plain")) {
            mText.setText(i.getStringExtra(Intent.EXTRA_TEXT));
        } else if (i.getType().contains("image/")) {
            Uri uri = (Uri) i.getParcelableExtra(Intent.EXTRA_STREAM);

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                addPicture(bitmap, null);
            } catch (IOException e) {
                if (DEBUG) {
                    Log.d(TAG, Log.getStackTraceString(e));
                }
            }
        }
    }
}

From source file:de.uni_koblenz_landau.apow.LoginActivity.java

@Override
protected void onNewIntent(Intent intent) {
    setIntent(intent);//from w  w  w . j  a va 2  s  .  c  o  m
    String action = intent.getAction();

    // If tag is detected, start reading it.
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) && MIME_TEXT_PLAIN.equals(intent.getType())) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        readNFCTag(tag);
    }
}

From source file:com.example.office.ui.Office365DemoActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {//from  w  w w . j av  a  2 s .c  o m
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();

        //Processing system intent of sharing an image
        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if (type.startsWith("image/")) {
                Bundle bundle = intent.getExtras();
                Uri uri = (Uri) bundle.get(Intent.EXTRA_STREAM);
                // Retrieving path to the image and attaching it to current intent
                attachImageToCurrentEvent(Utility.getRealPathFromURI(uri, this), type);
            }
        }

        if (savedInstanceState == null) {
            mSavedFragmentTag = null;
        } else {
            mSavedFragmentTag = savedInstanceState.getString(STATE_FRAGMENT_TAG);
        }

        setConfiguration();
    } catch (Exception e) {
        Logger.logApplicationException(e, getClass().getSimpleName() + ".onNewIntent(): Error.");
    }
}

From source file:me.myatminsoe.myansms.Message.java

/**
 * Get a {@link OnLongClickListener} to save the attachment.
 *
 * @param context {@link Context}/*from  ww  w.j av  a 2s . co m*/
 * @return {@link OnLongClickListener}
 */
public OnLongClickListener getSaveAttachmentListener(final Activity context) {
    if (contentIntent == null) {
        return null;
    }

    return new OnLongClickListener() {
        @Override
        public boolean onLongClick(final View v) {
            // check/request permission Manifest.permission.WRITE_EXTERNAL_STORAGE
            if (!SMSdroid.requestPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE, 0,
                    R.string.permissions_write_external_storage, null)) {
                return true;
            }

            try {
                String fn = ATTACHMENT_FILE;
                final Intent ci = Message.this.contentIntent;
                final String ct = ci.getType();
                if (ct == null) {
                    fn += "null";
                } else if (ct.startsWith("image/")) {
                    switch (ct) {
                    case "image/jpeg":
                        fn += "jpg";
                        break;
                    case "image/gif":
                        fn += "gif";
                        break;
                    default:
                        fn += "png";
                        break;
                    }
                } else if (ct.startsWith("audio/")) {
                    switch (ct) {
                    case "audio/3gpp":
                        fn += "3gpp";
                        break;
                    case "audio/mpeg":
                        fn += "mp3";
                        break;
                    case "audio/mid":
                        fn += "mid";
                        break;
                    default:
                        fn += "wav";
                        break;
                    }
                } else if (ct.startsWith("video/")) {
                    if (ct.equals("video/3gpp")) {
                        fn += "3gpp";
                    } else {
                        fn += "avi";
                    }
                } else {
                    fn += "ukn";
                }
                final File file = Message.this.createUniqueFile(Environment.getExternalStorageDirectory(), fn);
                //noinspection ConstantConditions
                InputStream in = context.getContentResolver().openInputStream(ci.getData());
                OutputStream out = new FileOutputStream(file);
                IOUtils.copy(in, out);
                out.flush();
                out.close();
                //noinspection ConstantConditions
                in.close();

                Toast.makeText(context, context.getString(R.string.attachment_saved) + " " + fn,
                        Toast.LENGTH_LONG).show();
                return true;
            } catch (IOException e) {

                Toast.makeText(context, R.string.attachment_not_saved, Toast.LENGTH_LONG).show();
            } catch (NullPointerException e) {

                Toast.makeText(context, R.string.attachment_not_saved, Toast.LENGTH_LONG).show();
            }
            return true;
        }
    };
}

From source file:com.studyjams.mdvideo.PlayerModule.ExoPlayerV2.PlayerActivityV2.java

/**debug?**/
//    @Override/*ww  w  .  j a va2s .c o m*/
//    public void onClick(View view) {
//        if (view == retryButton) {
//            initializePlayer();
//        } else if (view.getParent() == debugRootView) {
//            trackSelectionHelper.showSelectionDialog(this, ((Button) view).getText(),
//                    trackSelector.getCurrentSelections().info, (int) view.getTag());
//        }
//    }

// PlaybackControlView.VisibilityListener implementation
//
//    @Override
//    public void onVisibilityChange(int visibility) {
//        debugRootView.setVisibility(visibility);
//    }

// Internal methods
private void initializePlayer() {
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    String intentType = intent.getStringExtra(CONTENT_TYPE_INTENT);

    if (Intent.ACTION_SEND.equals(action) && type.equals("video/*")) {

        mContentUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
        mContentId = "";
        mContentPosition = C.TIME_UNSET;
        mSubtitleUri = null;
    } else if (intentType.equals(D.TYPE_VIDEO)) {

        mContentUri = intent.getData();
        mContentId = intent.getStringExtra(CONTENT_ID_EXTRA);
        mContentPosition = intent.getLongExtra(CONTENT_POSITION_EXTRA, 0);
        String subtitle = intent.getStringExtra(CONTENT_SUBTITLE_EXTRA);
        if (!TextUtils.isEmpty(subtitle)) {
            mSubtitleUri = Uri.parse(subtitle);
        } else {
            mSubtitleUri = null;
        }
        playerPosition = mContentPosition;
    } else if (intentType.equals(D.TYPE_SUBTITLE)) {
        mSubtitleUri = intent.getData();
    }

    if (player == null) {
        boolean preferExtensionDecoders = intent.getBooleanExtra(PREFER_EXTENSION_DECODERS, false);
        UUID drmSchemeUuid = intent.hasExtra(DRM_SCHEME_UUID_EXTRA)
                ? UUID.fromString(intent.getStringExtra(DRM_SCHEME_UUID_EXTRA))
                : null;
        DrmSessionManager<FrameworkMediaCrypto> drmSessionManager = null;
        if (drmSchemeUuid != null) {
            String drmLicenseUrl = intent.getStringExtra(DRM_LICENSE_URL);
            String[] keyRequestPropertiesArray = intent.getStringArrayExtra(DRM_KEY_REQUEST_PROPERTIES);
            Map<String, String> keyRequestProperties;
            if (keyRequestPropertiesArray == null || keyRequestPropertiesArray.length < 2) {
                keyRequestProperties = null;
            } else {
                keyRequestProperties = new HashMap<>();
                for (int i = 0; i < keyRequestPropertiesArray.length - 1; i += 2) {
                    keyRequestProperties.put(keyRequestPropertiesArray[i], keyRequestPropertiesArray[i + 1]);
                }
            }
            try {
                drmSessionManager = buildDrmSessionManager(drmSchemeUuid, drmLicenseUrl, keyRequestProperties);
            } catch (UnsupportedDrmException e) {
                int errorStringId = Util.SDK_INT < 18 ? R.string.error_drm_not_supported
                        : (e.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
                                ? R.string.error_drm_unsupported_scheme
                                : R.string.error_drm_unknown);
                showToast(errorStringId);
                return;
            }
        }

        eventLogger = new EventLogger();
        TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveVideoTrackSelection.Factory(
                BANDWIDTH_METER);
        trackSelector = new DefaultTrackSelector(mainHandler, videoTrackSelectionFactory);
        trackSelector.addListener(this);
        trackSelector.addListener(eventLogger);
        trackSelectionHelper = new TrackSelectionHelper(trackSelector, videoTrackSelectionFactory);
        player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, new DefaultLoadControl(),
                drmSessionManager, preferExtensionDecoders);
        player.addListener(this);
        player.addListener(eventLogger);
        player.setAudioDebugListener(eventLogger);
        player.setVideoDebugListener(eventLogger);
        player.setId3Output(eventLogger);
        simpleExoPlayerView.setPlayer(player);

        //?mediaController
        controller.setPlayer(player);
        controller.setTitle(mContentUri.getLastPathSegment());

        //            if (isTimelineStatic) {
        if (playerPosition == C.TIME_UNSET) {
            player.seekToDefaultPosition(playerWindow);
        } else {
            player.seekTo(playerWindow, playerPosition);
        }
        //            }
        player.setPlayWhenReady(shouldAutoPlay);

        /**?
        debugViewHelper = new DebugTextViewHelper(player, debugTextView);
        debugViewHelper.start();**/

        playerNeedsSource = true;
    }
    if (playerNeedsSource) {
        //            String action = intent.getAction();
        Uri[] uris;
        String[] extensions;
        if (ACTION_VIEW.equals(action)) {
            //                uris = new Uri[]{intent.getData()};
            uris = new Uri[] { mContentUri };
            extensions = new String[] { intent.getStringExtra(EXTENSION_EXTRA) };
        } else if (ACTION_VIEW_LIST.equals(action)) {
            String[] uriStrings = intent.getStringArrayExtra(URI_LIST_EXTRA);
            uris = new Uri[uriStrings.length];
            for (int i = 0; i < uriStrings.length; i++) {
                uris[i] = Uri.parse(uriStrings[i]);
            }
            extensions = intent.getStringArrayExtra(EXTENSION_LIST_EXTRA);
            if (extensions == null) {
                extensions = new String[uriStrings.length];
            }
        } else {
            showToast(getString(R.string.unexpected_intent_action, action));
            return;
        }
        if (Util.maybeRequestReadExternalStoragePermission(this, uris)) {
            // The player will be reinitialized if the permission is granted.
            return;
        }
        MediaSource[] mediaSources = new MediaSource[uris.length];
        for (int i = 0; i < uris.length; i++) {
            mediaSources[i] = buildMediaSource(uris[i], extensions[i]);
        }
        MediaSource mediaSource = mediaSources.length == 1 ? mediaSources[0]
                : new ConcatenatingMediaSource(mediaSources);
        player.prepare(mediaSource, !isTimelineStatic, !isTimelineStatic);
        playerNeedsSource = false;
        //            updateButtonVisibilities();
    }
}

From source file:de.earthlingz.oerszebra.DroidZebra.java

@Override
protected void onNewIntent(Intent intent) {

    String action = intent.getAction();
    String type = intent.getType();

    Log.i("Intent", type + " " + action);

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        switch (type) {
        case "text/plain":
            setUpBoard(intent.getDataString()); // Handle text being sent

            break;
        case "message/rfc822":
            Log.i("Intent", intent.getStringExtra(Intent.EXTRA_TEXT));
            setUpBoard(intent.getStringExtra(Intent.EXTRA_TEXT)); // Handle text being sent

            break;
        default:/*from   w w w . ja v a  2s  . co  m*/
            Log.e("intent", "unknown intent");
            break;
        }
    } else {
        Log.e("intent", "unknown intent");
    }
}

From source file:itcr.gitsnes.MainActivity.java

/** On function onActivityResult is handle the results to load file from directories
 * and load image from galery, next the results the objects are save on file of bytes
 *//*w  ww .j ava2 s.  co  m*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    uiHelper.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && flag) {
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            String type = data.getType();
            if (uri != null) {
                String path = uri.toString();
                if (path.toLowerCase().startsWith("file://")) {
                    this.s3game = new File(URI.create(path));
                    Log.i(TAG, "archivo cargado");
                }
            }
        }
    }

    /* Handle file/image pick intent and convert that into a media storaged data*/
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data && !flag) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        this.s3image = new File(picturePath);
        Log.i(TAG, "imagen cargado");
    }

}

From source file:com.dycody.android.idealnote.MainActivity.java

private boolean receivedIntent(Intent i) {
    return Constants.ACTION_SHORTCUT.equals(i.getAction())
            || Constants.ACTION_NOTIFICATION_CLICK.equals(i.getAction())
            || Constants.ACTION_WIDGET.equals(i.getAction())
            || Constants.ACTION_TAKE_PHOTO.equals(i.getAction())
            || ((Intent.ACTION_SEND.equals(i.getAction()) || Intent.ACTION_SEND_MULTIPLE.equals(i.getAction())
                    || Constants.INTENT_GOOGLE_NOW.equals(i.getAction())) && i.getType() != null)
            || i.getAction().contains(Constants.ACTION_NOTIFICATION_CLICK);
}

From source file:de.kodejak.hashr.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();//from  w  w  w. ja  va2  s  .co  m

    // Set a toolbar which will replace the action bar.
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout),
            toolbar);

    Intent intent = getIntent();
    String action = intent.getAction();

    if (action.compareTo(Intent.ACTION_VIEW) == 0) {
        String scheme = intent.getScheme();
        ContentResolver resolver = getContentResolver();

        if (scheme.compareTo(ContentResolver.SCHEME_CONTENT) == 0) {
            Uri uri = intent.getData();
            String name = getContentName(resolver, uri);

            Log.v("tag", "Content intent detected: " + action + " : " + intent.getDataString() + " : "
                    + intent.getType() + " : " + name);
            //What TODO?
        } else if (scheme.compareTo(ContentResolver.SCHEME_FILE) == 0) {
            lastSumFile = intent.getData().getPath();
            forcedFragmentNum = prepareOpenSumFile(lastSumFile);

            if (forcedFragmentNum > -1) {
                mNavigationDrawerFragment.selectItem(forcedFragmentNum);
            }
        }
    }
}

From source file:com.openerp.addons.messages.MessageComposeActivty.java

/**
 * Handle message intent filter for attachments
 * //from  w  ww  . j  a v  a2 s  .  c  o  m
 * @param intent
 */
private void handleIntentFilter(Intent intent) {
    attachments_type.put(ATTACHMENT_TYPE.IMAGE, "image/*");
    attachments_type.put(ATTACHMENT_TYPE.TEXT_FILE, "application/*");

    String action = intent.getAction();
    String type = intent.getType();

    // Single attachment
    if (Intent.ACTION_SEND.equals(action) && type != null) {
        Uri fileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
        file_uris.add(fileUri);
        handleReceivedFile();
    }

    // Multiple Attachments
    if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
        ArrayList<Uri> fileUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        file_uris.addAll(fileUris);
        handleReceivedFile();

    }

    // note.note send as mail
    if (intent.hasExtra("note_body")) {
        EditText edtBody = (EditText) findViewById(R.id.edtMessageBody);
        String body = intent.getExtras().getString("note_body");
        edtBody.setText(HTMLHelper.stringToHtml(body));
        is_note_body = true;
    }

}