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:com.trellmor.mocklocationpicture.MLPActivity.java

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

    mImagePreview = (ImageView) findViewById(R.id.image_preview);

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

    if (Intent.ACTION_SEND.equals(action) && type != null && type.startsWith("image/")) {
        // Started by share intent, display preview image
        setImageUri((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
        intent.setAction("");
    } else if (savedInstanceState != null) {
        setImageUri((Uri) savedInstanceState.getParcelable(KEY_IMAGE_URI));
    }/* w ww. j a va  2 s. c o m*/
}

From source file:com.farmerbb.notepad.activity.NoteEditActivity.java

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

    // Apply theme
    SharedPreferences pref = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE);
    String theme = pref.getString("theme", "light-sans");

    LinearLayout noteViewEdit = findViewById(R.id.noteViewEdit);

    if (theme.contains("light"))
        noteViewEdit.setBackgroundColor(ContextCompat.getColor(this, R.color.window_background));

    if (theme.contains("dark"))
        noteViewEdit.setBackgroundColor(ContextCompat.getColor(this, R.color.window_background_dark));

    // Set action bar elevation
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        getSupportActionBar().setElevation(getResources().getDimensionPixelSize(R.dimen.action_bar_elevation));

    if (!(getSupportFragmentManager().findFragmentById(R.id.noteViewEdit) instanceof NoteEditFragment)) {
        // Handle intents
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();

        // Intent sent through an external application
        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if ("text/plain".equals(type)) {
                external = getExternalContent();
                if (external != null) {
                    newNote();//ww  w  .  j  av a 2  s  .  co  m
                } else {
                    showToast(R.string.loading_external_file);
                    finish();
                }
            } else {
                showToast(R.string.loading_external_file);
                finish();
            }

            // Intent sent through Google Now "note to self"
        } else if ("com.google.android.gm.action.AUTO_SEND".equals(action) && type != null) {
            if ("text/plain".equals(type)) {
                external = getExternalContent();
                if (external != null) {
                    try {
                        // Write note to disk
                        FileOutputStream output = openFileOutput(String.valueOf(System.currentTimeMillis()),
                                Context.MODE_PRIVATE);
                        output.write(external.getBytes());
                        output.close();

                        // Show toast notification and finish
                        showToast(R.string.note_saved);
                        finish();
                    } catch (IOException e) {
                        // Show error message as toast if file fails to save
                        showToast(R.string.failed_to_save);
                        finish();
                    }
                }
            }
        } else if (Intent.ACTION_EDIT.equals(action) && "text/plain".equals(type)) {
            external = intent.getStringExtra(Intent.EXTRA_TEXT);
            if (external != null) {
                newNote();
                return;
            }
            finish();
        } else if (Intent.ACTION_VIEW.equals(action) && "text/plain".equals(type)) {
            try {
                InputStream in = getContentResolver().openInputStream(intent.getData());
                Reader rd = new InputStreamReader(in, "UTF-8");
                char[] buffer = new char[4096];
                int len;
                StringBuilder sb = new StringBuilder();
                while ((len = rd.read(buffer)) != -1) {
                    sb.append(buffer, 0, len);
                }
                rd.close();
                in.close();
                external = sb.toString();
            } catch (Exception e) {
                // show msg error loading data?
            }
            if (external != null) {
                newNote();
                return;
            }
            finish();
        } else
            newNote();
    }
}

From source file:de.evilbrain.sendtosftp.Main.java

@SuppressLint("NewApi")
private void handlePushFromApp() {
    // Push to this app
    Intent intent = getIntent();
    String type = intent.getType();

    if (type != null) {

        // Set all visible
        fileNameText.setVisibility(View.VISIBLE);
        fileName.setVisibility(View.VISIBLE);
        imagePreview.setVisibility(View.VISIBLE);
        buttonSend.setVisibility(View.VISIBLE);

        // get Content
        String contentString = "";
        Object content = null;/*from   w w  w  . ja v  a2  s.c om*/

        if (android.os.Build.VERSION.SDK_INT > 16) {
            content = intent.getClipData().getItemAt(0).getUri();
            contentString = content.toString();
        } else {
            content = intent.getExtras().get(Intent.EXTRA_STREAM);
            contentString = content.toString();
        }

        // set filename
        fileName.setText(contentString);

        // Preview Image
        if (type.contains("image")) {
            imagePreview.setImageURI((Uri) content);
        }
    }
}

From source file:com.albedinsky.android.support.intent.ContentIntentTest.java

public void testBuildWithInputUri() {
    mIntent.input(Uri.parse("content://android/data/images/lion.jpg"));
    mIntent.dataType(MimeType.IMAGE_JPEG);

    final Intent intent = mIntent.build();
    assertNotNull(intent);/*from   w ww  .  j  a  v a  2 s .c  om*/
    assertEquals(Intent.ACTION_VIEW, intent.getAction());
    assertEquals(Uri.parse("content://android/data/images/lion.jpg"), intent.getData());
    assertEquals(MimeType.IMAGE_JPEG, intent.getType());
}

From source file:com.google.cloud.android.language.MainActivity.java

private void handleShareIntent() {
    final Intent intent = getIntent();
    if (TextUtils.equals(intent.getAction(), Intent.ACTION_SEND)
            && TextUtils.equals(intent.getType(), "text/plain")) {
        String text = intent.getStringExtra(Intent.EXTRA_TEXT);
        if (text != null) {
            mInput.setText(text);/* w ww.j  av a2s  . com*/
        }
    }
}

From source file:de.msal.shoutemo.fragments.ChatFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    /* receive and handle share intent */
    Intent intent = getActivity().getIntent();
    String type = intent.getType();
    if (intent.getAction().equals(Intent.ACTION_SEND) && type != null) {
        if (type.equals("text/plain")) {
            String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
            if (sharedText != null) {
                mInputField.setText(sharedText);
            }/*www.j  a v a  2s  .  c  o m*/
        }
    }

    /* hide send-button, if no text is entered */
    mInputField.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) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (mSendButton.getVisibility() == View.VISIBLE && s.length() == 0) {
                Animation pushOut = AnimationUtils.loadAnimation(getActivity(), R.anim.push_out);
                mSendButton.startAnimation(pushOut);
                mSendButton.setVisibility(View.GONE);
            } else if (mSendButton.getVisibility() == View.GONE && s.length() >= 1) {
                Animation pushIn = AnimationUtils.loadAnimation(getActivity(), R.anim.push_in);
                mSendButton.startAnimation(pushIn);
                mSendButton.setVisibility(View.VISIBLE);
            }
        }
    });

    /*  */
    mInputField.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mKeyboardButton.setImageResource(R.drawable.ic_action_keyboard_alt_white_24dp);
            mEmoticonGrid.setVisibility(View.GONE);
        }
    });
}

From source file:com.ekeitho.sound.MainActivity.java

private String handleIncomingIntentShareIfAny() {
    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    /* soundclouds share link comes in second and will not have a split
       greater than 0! hackity hack hack!
     *//* w  w  w.ja v a  2 s.c  om*/
    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            String input = intent.getStringExtra(Intent.EXTRA_TEXT);
            return input.split("\n")[1];
        }
    }
    return null;
}

From source file:org.akvo.caddisfly.ui.ExternalActionActivity.java

@Override
protected void onStart() {
    super.onStart();

    Intent intent = getIntent();
    String type = intent.getType();

    if (type != null && "text/plain".equals(type)
            && AppConfig.FLOW_ACTION_EXTERNAL_SOURCE.equals(intent.getAction())
            || AppConfig.FLOW_ACTION_CADDISFLY.equals(intent.getAction())) {

        mTestTypeUuid = intent.getStringExtra(SensorConstants.RESOURCE_ID);

        mIsExternalAppCall = true;//from www  .ja  v a  2s. c o m
        mExternalAppLanguageCode = intent.getStringExtra(SensorConstants.LANGUAGE);
        CaddisflyApp.getApp().setAppLanguage(mExternalAppLanguageCode, mIsExternalAppCall, handler);
        String questionTitle = intent.getStringExtra(SensorConstants.QUESTION_TITLE);

        if (AppConfig.FLOW_ACTION_EXTERNAL_SOURCE.equals(intent.getAction())) {

            // old version of survey does not expect image in result
            mCallerExpectsImageInResult = false;
        }

        if (mTestTypeUuid == null) {

            //todo: remove when obsolete
            //UUID was not found so it must be old version survey, look for 5 letter code
            String code = questionTitle.trim().substring(Math.max(0, questionTitle.length() - 5)).toLowerCase();

            if (code.equalsIgnoreCase("strip")) {
                final Intent colorimetricStripIntent = new Intent(this, TestTypeListActivity.class);
                colorimetricStripIntent.putExtra(Constant.SEND_IMAGE_IN_RESULT, mCallerExpectsImageInResult);
                startActivityForResult(colorimetricStripIntent, REQUEST_TEST);
                return;
            }

            mTestTypeUuid = TestConfigHelper.getUuidFromShortCode(code);

        }

        //Get the test config by uuid
        CaddisflyApp.getApp().loadTestConfigurationByUuid(mTestTypeUuid);

        if (CaddisflyApp.getApp().getCurrentTestInfo() == null) {
            ((TextView) findViewById(R.id.textTitle)).setText(getTestName(questionTitle));
            alertTestTypeNotSupported();
        } else {
            ((TextView) findViewById(R.id.textTitle))
                    .setText(CaddisflyApp.getApp().getCurrentTestInfo().getName());

            String[] permissions = {};
            if (CaddisflyApp.getApp().getCurrentTestInfo().requiresCameraFlash()) {
                if (AppPreferences.useExternalCamera()) {
                    permissions = new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE };
                } else {
                    permissions = new String[] { Manifest.permission.CAMERA,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE };
                }
            }

            if (!ApiUtil.hasPermissions(this, permissions)) {
                ActivityCompat.requestPermissions(this, permissions, PERMISSION_ALL);
            } else {
                startTest(mTestTypeUuid);
            }
        }
    }
}

From source file:com.silentcircle.contacts.activities.ScContactDetailActivity.java

@Override
protected void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    if (PhoneCapabilityTester.isUsingTwoPanes(this)) {
        // This activity must not be shown. We have to select the contact in the
        // PeopleActivity instead ==> Create a forward intent and finish
        final Intent originalIntent = getIntent();
        Intent intent = new Intent();
        intent.setAction(originalIntent.getAction());
        intent.setDataAndType(originalIntent.getData(), originalIntent.getType());

        // If we are launched from the outside, we should create a new task, because the user
        // can freely navigate the app (this is different from phones, where only the UP button
        // kicks the user into the full app)
        if (NavUtils.shouldUpRecreateTask(this, intent)) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
                    | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
        } else {//from ww  w.j  a va2s .  c  om
            intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_FORWARD_RESULT
                    | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }

        intent.setClass(this, ScContactsMainActivity.class);
        startActivity(intent);
        finish();
        return;
    }

    setContentView(R.layout.contact_detail_activity);

    mContactDetailLayoutController = new ContactDetailLayoutController(this, savedState,
            getSupportFragmentManager(), null, findViewById(R.id.contact_detail_container),
            mContactDetailFragmentListener);

    // We want the UP affordance but no app icon.
    // Setting HOME_AS_UP, SHOW_TITLE and clearing SHOW_HOME does the trick.
    ActionBar actionBar = this.getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE,
                ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_HOME);
        actionBar.setTitle("");
    }

    Log.i(TAG, getIntent().getData().toString());
}

From source file:us.shandian.blacklight.ui.statuses.NewPostActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().setUiOptions(ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.post_status);

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

    // Init/*from ww  w  .  j  a  v  a2s .co m*/
    mText = (EditText) findViewById(R.id.post_edit);
    mBackground = (ImageView) findViewById(R.id.post_back);
    mCount = (TextView) findViewById(R.id.post_count);
    mDrawer = (DrawerLayout) findViewById(R.id.post_drawer);

    // 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);
        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);
        }
    });

    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);
        }
    });

    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) {

        }

        @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(getResources().getColor(R.color.gray));
                    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 (mEmoticonMenu != null) {
                if (mIsLong) {
                    getFragmentManager().beginTransaction().replace(R.id.post_emoticons, mColorPickerFragment)
                            .commit();
                    mEmoticonMenu.setIcon(R.drawable.ic_action_edit);
                    mEmoticonMenu.setTitle(R.string.color);
                } else {
                    getFragmentManager().beginTransaction().replace(R.id.post_emoticons, mEmoticonFragment)
                            .commit();
                    mEmoticonMenu.setIcon(R.drawable.ic_action_emoticon);
                    mEmoticonMenu.setTitle(R.string.emoticon);
                }
            }
        }
    });

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

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

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