Example usage for android.content Intent EXTRA_STREAM

List of usage examples for android.content Intent EXTRA_STREAM

Introduction

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

Prototype

String EXTRA_STREAM

To view the source code for android.content Intent EXTRA_STREAM.

Click Source Link

Document

A content: URI holding a stream of data associated with the Intent, used with #ACTION_SEND to supply the data being sent.

Usage

From source file:de.baumann.hhsmoodle.data_notes.Notes_Fragment.java

public void setNotesList() {

    if (isFABOpen) {
        closeFABMenu();/*w  w w . ja  va2s  . c  om*/
    }

    //display data
    final int layoutstyle = R.layout.list_item_notes;
    int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.textView_create_notes };
    String[] column = new String[] { "note_title", "note_content", "note_creation" };
    final Cursor row = db.fetchAllData(getActivity());
    adapter = new SimpleCursorAdapter(getActivity(), layoutstyle, row, column, xml_id, 0) {
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String note_title = row2.getString(row2.getColumnIndexOrThrow("note_title"));
            final String note_content = row2.getString(row2.getColumnIndexOrThrow("note_content"));
            final String note_icon = row2.getString(row2.getColumnIndexOrThrow("note_icon"));
            final String note_attachment = row2.getString(row2.getColumnIndexOrThrow("note_attachment"));
            final String note_creation = row2.getString(row2.getColumnIndexOrThrow("note_creation"));

            View v = super.getView(position, convertView, parent);
            ImageView iv_icon = (ImageView) v.findViewById(R.id.icon_notes);
            ImageView iv_attachment = (ImageView) v.findViewById(R.id.att_notes);
            helper_main.switchIcon(getActivity(), note_icon, "note_icon", iv_icon);

            switch (note_attachment) {
            case "":
                iv_attachment.setVisibility(View.GONE);
                break;
            default:
                iv_attachment.setVisibility(View.VISIBLE);
                iv_attachment.setImageResource(R.drawable.ic_attachment);
                break;
            }

            File file = new File(note_attachment);
            if (!file.exists()) {
                iv_attachment.setVisibility(View.GONE);
            }

            iv_icon.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    final helper_main.Item[] items = {
                            new helper_main.Item(getString(R.string.note_priority_0), R.drawable.circle_green),
                            new helper_main.Item(getString(R.string.note_priority_1), R.drawable.circle_yellow),
                            new helper_main.Item(getString(R.string.note_priority_2), R.drawable.circle_red), };

                    ListAdapter adapter = new ArrayAdapter<helper_main.Item>(getActivity(),
                            android.R.layout.select_dialog_item, android.R.id.text1, items) {
                        @NonNull
                        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                            //Use super class to create the View
                            View v = super.getView(position, convertView, parent);
                            TextView tv = (TextView) v.findViewById(android.R.id.text1);
                            tv.setTextSize(18);
                            tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon, 0, 0, 0);
                            //Add margin between image and text (support various screen densities)
                            int dp5 = (int) (24 * getResources().getDisplayMetrics().density + 0.5f);
                            tv.setCompoundDrawablePadding(dp5);

                            return v;
                        }
                    };

                    new AlertDialog.Builder(getActivity())
                            .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int whichButton) {
                                    dialog.cancel();
                                }
                            }).setAdapter(adapter, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int item) {
                                    if (item == 0) {
                                        db.update(Integer.parseInt(_id), note_title, note_content, "3",
                                                note_attachment, note_creation);
                                        setNotesList();
                                    } else if (item == 1) {
                                        db.update(Integer.parseInt(_id), note_title, note_content, "2",
                                                note_attachment, note_creation);
                                        setNotesList();
                                    } else if (item == 2) {
                                        db.update(Integer.parseInt(_id), note_title, note_content, "1",
                                                note_attachment, note_creation);
                                        setNotesList();
                                    }
                                }
                            }).show();
                }
            });
            iv_attachment.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    helper_main.openAtt(getActivity(), lv, note_attachment);
                }
            });
            return v;
        }
    };

    //display data by filter
    final String note_search = sharedPref.getString("filter_noteBY", "note_title");
    sharedPref.edit().putString("filter_noteBY", "note_title").apply();
    filter.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return db.fetchDataByFilter(constraint.toString(), note_search);
        }
    });

    lv.setAdapter(adapter);
    //onClick function
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {

            if (isFABOpen) {
                closeFABMenu();
            }

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String note_title = row2.getString(row2.getColumnIndexOrThrow("note_title"));
            final String note_content = row2.getString(row2.getColumnIndexOrThrow("note_content"));
            final String note_icon = row2.getString(row2.getColumnIndexOrThrow("note_icon"));
            final String note_attachment = row2.getString(row2.getColumnIndexOrThrow("note_attachment"));
            final String note_creation = row2.getString(row2.getColumnIndexOrThrow("note_creation"));

            final Button attachment;
            final TextView textInput;

            LayoutInflater inflater = getActivity().getLayoutInflater();

            final ViewGroup nullParent = null;
            final View dialogView = inflater.inflate(R.layout.dialog_note_show, nullParent);

            final String attName = note_attachment.substring(note_attachment.lastIndexOf("/") + 1);
            final String att = getString(R.string.app_att) + ": " + attName;

            attachment = (Button) dialogView.findViewById(R.id.button_att);
            if (attName.equals("")) {
                attachment.setVisibility(View.GONE);
            } else {
                attachment.setText(att);
            }

            textInput = (TextView) dialogView.findViewById(R.id.note_text_input);
            if (note_content.isEmpty()) {
                textInput.setVisibility(View.GONE);
            } else {
                textInput.setText(note_content);
                Linkify.addLinks(textInput, Linkify.WEB_URLS);
            }

            attachment.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    helper_main.openAtt(getActivity(), textInput, note_attachment);
                }
            });

            final ImageView be = (ImageView) dialogView.findViewById(R.id.imageButtonPri);
            final ImageView attImage = (ImageView) dialogView.findViewById(R.id.attImage);

            File file2 = new File(note_attachment);
            if (!file2.exists()) {
                attachment.setVisibility(View.GONE);
                attImage.setVisibility(View.GONE);
            } else if (note_attachment.contains(".gif") || note_attachment.contains(".bmp")
                    || note_attachment.contains(".tiff") || note_attachment.contains(".png")
                    || note_attachment.contains(".jpg") || note_attachment.contains(".JPG")
                    || note_attachment.contains(".jpeg") || note_attachment.contains(".mpeg")
                    || note_attachment.contains(".mp4") || note_attachment.contains(".3gp")
                    || note_attachment.contains(".3g2") || note_attachment.contains(".avi")
                    || note_attachment.contains(".flv") || note_attachment.contains(".h261")
                    || note_attachment.contains(".h263") || note_attachment.contains(".h264")
                    || note_attachment.contains(".asf") || note_attachment.contains(".wmv")) {
                attImage.setVisibility(View.VISIBLE);

                try {
                    Glide.with(getActivity()).load(note_attachment) // or URI/path
                            .diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).into(attImage); //imageView to set thumbnail to
                } catch (Exception e) {
                    Log.w("HHS_Moodle", "Error load thumbnail", e);
                    attImage.setVisibility(View.GONE);
                }

                attImage.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        helper_main.openAtt(getActivity(), attImage, note_attachment);
                    }
                });
            }

            switch (note_icon) {
            case "3":
                be.setImageResource(R.drawable.circle_green);
                break;
            case "2":
                be.setImageResource(R.drawable.circle_yellow);
                break;
            case "1":
                be.setImageResource(R.drawable.circle_red);
                break;
            }

            android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(getActivity())
                    .setTitle(note_title).setView(dialogView)
                    .setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setNegativeButton(R.string.note_edit, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            sharedPref.edit().putString("handleTextTitle", note_title)
                                    .putString("handleTextText", note_content)
                                    .putString("handleTextIcon", note_icon).putString("handleTextSeqno", _id)
                                    .putString("handleTextAttachment", note_attachment)
                                    .putString("handleTextCreate", note_creation).apply();
                            helper_main.switchToActivity(getActivity(), Activity_EditNote.class, false);
                        }
                    });
            dialog.show();
        }
    });

    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            if (isFABOpen) {
                closeFABMenu();
            }

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String note_title = row2.getString(row2.getColumnIndexOrThrow("note_title"));
            final String note_content = row2.getString(row2.getColumnIndexOrThrow("note_content"));
            final String note_icon = row2.getString(row2.getColumnIndexOrThrow("note_icon"));
            final String note_attachment = row2.getString(row2.getColumnIndexOrThrow("note_attachment"));
            final String note_creation = row2.getString(row2.getColumnIndexOrThrow("note_creation"));

            final CharSequence[] options = { getString(R.string.number_edit_entry),
                    getString(R.string.bookmark_remove_bookmark), getString(R.string.todo_share),
                    getString(R.string.todo_menu), getString(R.string.count_create),
                    getString(R.string.bookmark_createEvent) };
            new AlertDialog.Builder(getActivity())
                    .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (options[item].equals(getString(R.string.number_edit_entry))) {
                                Notes_helper.newNote(getActivity(), note_title, note_content, note_icon,
                                        note_attachment, note_creation, _id);
                            }

                            if (options[item].equals(getString(R.string.todo_share))) {
                                File attachment = new File(note_attachment);
                                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                                sharingIntent.setType("text/plain");
                                sharingIntent.putExtra(Intent.EXTRA_SUBJECT, note_title);
                                sharingIntent.putExtra(Intent.EXTRA_TEXT, note_content);

                                if (attachment.exists()) {
                                    Uri bmpUri = Uri.fromFile(attachment);
                                    sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                                }

                                startActivity(Intent.createChooser(sharingIntent,
                                        (getString(R.string.note_share_2))));
                            }

                            if (options[item].equals(getString(R.string.todo_menu))) {
                                Todo_helper.newTodo(getActivity(), note_title, note_content,
                                        getActivity().getString(R.string.note_content));
                            }

                            if (options[item].equals(getString(R.string.count_create))) {
                                Count_helper.newCount(getActivity(), note_title, note_content,
                                        getActivity().getString(R.string.note_content), false);
                            }

                            if (options[item].equals(getString(R.string.bookmark_createEvent))) {
                                helper_main.createCalendarEvent(getActivity(), note_title, note_content);
                            }

                            if (options[item].equals(getString(R.string.bookmark_remove_bookmark))) {
                                Snackbar snackbar = Snackbar
                                        .make(lv, R.string.note_remove_confirmation, Snackbar.LENGTH_LONG)
                                        .setAction(R.string.toast_yes, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                db.delete(Integer.parseInt(_id));
                                                setNotesList();
                                            }
                                        });
                                snackbar.show();
                            }
                        }
                    }).show();

            return true;
        }
    });
}

From source file:net.emilymaier.movebot.MoveBotActivity.java

/**
 * Generate a run's .gpx file and share it.
 * @param run the run session to generate the .gpx from
 *//*from w  ww.java2  s.c o  m*/
private void shareGpx(Run run) {
    String filename;
    try {
        filename = run.generateGpx(this);
    } catch (IOException e) {
        throw new RuntimeException("IOException", e);
    }
    File gpxFile = new File(getFilesDir(), filename);
    Uri gpxUri = FileProvider.getUriForFile(this, "net.emilymaier.movebot.fileprovider", gpxFile);
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_STREAM, gpxUri);
    sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    sendIntent.setType("application/xml");
    startActivity(sendIntent);
}

From source file:com.mahali.gpslogger.MainActivity.java

private void shareSession(GPSSession sess) {
    File mSessFile = new File(dirFile.getPath(), sess.getFileName());

    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mSessFile));
    sendIntent.setType("application/octet-stream"); // This seems to be a good MIME type for raw binary data
    startActivity(sendIntent);//from w  w  w  .  jav a 2s.  com
}

From source file:org.andstatus.app.msg.TimelineActivity.java

private void parseNewIntent(Intent intentNew) {
    if (MyLog.isVerboseEnabled()) {
        MyLog.v(this, "parseNewIntent:" + intentNew);
    }/*from  w  ww . j a v a  2 s . co m*/
    mRateLimitText = "";
    mListParametersNew.setTimelineType(TimelineType.UNKNOWN);
    mListParametersNew.myAccountUserId = MyContextHolder.get().persistentAccounts().getCurrentAccountUserId();
    mListParametersNew.mSelectedUserId = 0;
    parseAppSearchData(intentNew);
    if (mListParametersNew.getTimelineType() == TimelineType.UNKNOWN) {
        mListParametersNew.parseIntentData(intentNew);
    }
    if (mListParametersNew.getTimelineType() == TimelineType.UNKNOWN) {
        /* Set default values */
        mListParametersNew.setTimelineType(TimelineType.HOME);
        mListParametersNew.mSearchQuery = "";
    }
    if (mListParametersNew.getTimelineType() == TimelineType.USER) {
        if (mListParametersNew.mSelectedUserId == 0) {
            mListParametersNew.mSelectedUserId = mListParametersNew.myAccountUserId;
        }
    } else {
        mListParametersNew.mSelectedUserId = 0;
    }

    if (Intent.ACTION_SEND.equals(intentNew.getAction())) {
        shareViaThisApplication(intentNew.getStringExtra(Intent.EXTRA_SUBJECT),
                intentNew.getStringExtra(Intent.EXTRA_TEXT),
                (Uri) intentNew.getParcelableExtra(Intent.EXTRA_STREAM));
    }
}

From source file:com.sentaroh.android.BluetoothWidget.Log.LogFileListDialogFragment.java

private void sendLogFile(final LogFileListAdapter lfm_adapter) {
    final String zip_file_name = mGlblParms.settingsLogFileDir + "log.zip";

    int no_of_files = 0;
    for (int i = 0; i < lfm_adapter.getCount(); i++) {
        if (lfm_adapter.getItem(i).isChecked)
            no_of_files++;// w  w w . j  a  va 2s  .c o  m
    }
    final String[] file_name = new String[no_of_files];
    int files_pos = 0;
    for (int i = 0; i < lfm_adapter.getCount(); i++) {
        if (lfm_adapter.getItem(i).isChecked) {
            file_name[files_pos] = lfm_adapter.getItem(i).log_file_path;
            files_pos++;
        }
    }
    final ThreadCtrl tc = new ThreadCtrl();
    NotifyEvent ntfy = new NotifyEvent(mContext);
    ntfy.setListener(new NotifyEventListener() {
        @Override
        public void positiveResponse(Context c, Object[] o) {
        }

        @Override
        public void negativeResponse(Context c, Object[] o) {
            tc.setDisabled();
        }
    });

    final ProgressBarDialogFragment pbdf = ProgressBarDialogFragment.newInstance(
            mContext.getString(R.string.msgs_log_file_list_dlg_send_zip_file_creating), "",
            mContext.getString(R.string.msgs_common_dialog_cancel),
            mContext.getString(R.string.msgs_common_dialog_cancel));
    pbdf.showDialog(getFragmentManager(), pbdf, ntfy, true);
    Thread th = new Thread() {
        @Override
        public void run() {
            File lf = new File(zip_file_name);
            lf.delete();
            String[] lmp = LocalMountPoint.convertFilePathToMountpointFormat(mContext, file_name[0]);
            ZipUtil.createZipFile(mContext, tc, pbdf, zip_file_name, lmp[0], file_name);
            if (tc.isEnabled()) {
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(Intent.ACTION_SEND);
                //                intent.setType("message/rfc822");  
                //                intent.setType("text/plain");
                intent.setType("application/zip");
                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(lf));
                mFragment.getActivity().startActivity(intent);

                mUiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        lfm_adapter.setAllItemChecked(false);
                        lfm_adapter.setShowCheckBox(false);
                        lfm_adapter.notifyDataSetChanged();
                        setContextButtonNormalMode(lfm_adapter);
                    }
                });
            } else {
                lf.delete();

                MessageDialogFragment mdf = MessageDialogFragment.newInstance(false, "W",
                        mContext.getString(R.string.msgs_log_file_list_dlg_send_zip_file_cancelled), "");
                mdf.showDialog(mFragment.getFragmentManager(), mdf, null);

            }
            pbdf.dismiss();
        };
    };
    th.start();
}

From source file:org.alfresco.mobile.android.application.fragments.browser.ChildrenBrowserFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case PublicIntent.REQUESTCODE_FILEPICKER:
        if (data != null && IntentIntegrator.ACTION_PICK_FILE.equals(data.getAction())) {
            ActionManager.actionPickFile(getFragmentManager().findFragmentByTag(TAG),
                    IntentIntegrator.REQUESTCODE_FILEPICKER);
        } else if (data != null && data.getData() != null) {
            String tmpPath = ActionManager.getPath(getActivity(), data.getData());
            if (tmpPath != null) {
                tmpFile = new File(tmpPath);
            } else {
                // Error case : Unable to find the file path associated
                // to user pick.
                // Sample : Picasa image case
                ActionManager.actionDisplayError(this,
                        new AlfrescoAppException(getString(R.string.error_unknown_filepath), true));
            }//from w  w w .j a v  a  2  s.c  o m
        } else if (data != null && data.getExtras() != null
                && data.getExtras().containsKey(Intent.EXTRA_STREAM)) {
            List<File> files = new ArrayList<File>();
            List<Uri> uris = data.getExtras().getParcelableArrayList(Intent.EXTRA_STREAM);
            for (Uri uri : uris) {
                files.add(new File(ActionManager.getPath(getActivity(), uri)));
            }
            createFiles(files);
        }
        break;
    default:
        break;
    }
}

From source file:com.kitware.tangoproject.paraviewtangorecorder.PointCloudActivity.java

private void record_SwitchChanged(boolean isChecked) {
    try {/* w  ww.j  a  v  a 2  s .c om*/
        mutex_on_mIsRecording.acquire();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    mIsRecording = isChecked;
    // Start Recording
    if (mIsRecording) {
        // Generate a new date number to create a new group of files
        Calendar rightNow = Calendar.getInstance();
        int hour = rightNow.get(Calendar.HOUR_OF_DAY);
        int minute = rightNow.get(Calendar.MINUTE);
        int sec = rightNow.get(Calendar.SECOND);
        int milliSec = rightNow.get(Calendar.MILLISECOND);
        mNowTimeString = "" + (int) (1000000 * hour + 10000 * minute + 100 * sec + (float) milliSec / 10.0);
        mNumberOfFilesWritten = 0;
        // Enable snapshot button
        mTakeSnapButton.setEnabled(true);
    }
    // Finish Recording
    else {
        // Disable snapshot button
        mTakeSnapButton.setEnabled(false);
        // Display a waiting progress bar
        mWaitingTextView.setText(R.string.waitSavingScan);
        mWaitingLinearLayout.setVisibility(View.VISIBLE);
        // Background task for writing poses to file
        class SendCommandTask extends AsyncTask<Context, Void, Uri> {
            /** The system calls this to perform work in a worker thread and
             * delivers it the parameters given to AsyncTask.execute() */
            @Override
            protected Uri doInBackground(Context... myAppContext) {

                // Stop the Pose Recording, and write them to a file.
                writePoseToFile(mNumPoseInSequence);
                // If a snap has been asked just before, but not saved, ignore it, otherwise,
                // it will be saved at the end dof this function, and the 2nd archive will override
                // the first.
                mTimeToTakeSnap = false;
                mNumPoseInSequence = 0;
                mPoseOrientationBuffer.clear();
                mPoseOrientationBuffer.clear();
                mPoseTimestampBuffer.clear();

                // Zip all the files from this sequence
                String zipFilename = mSaveDirAbsPath + "TangoData_" + mNowTimeString + "_"
                        + mFilenameBuffer.size() + "files.zip";
                String[] fileList = mFilenameBuffer.toArray(new String[mFilenameBuffer.size()]);
                ZipWriter zipper = new ZipWriter(fileList, zipFilename);
                zipper.zip();

                // Delete the data files now that they are archived
                for (String s : mFilenameBuffer) {
                    File file = new File(s);
                    boolean deleted = file.delete();
                    if (!deleted) {
                        Log.w(TAG, "File \"" + s + "\" not deleted\n");
                    }
                }
                mFilenameBuffer.clear();

                // Send the zip file to another app
                File myZipFile = new File(zipFilename);

                return FileProvider.getUriForFile(myAppContext[0],
                        "com.kitware." + "tangoproject.paraviewtangorecorder.fileprovider", myZipFile);
            }

            /** The system calls this to perform work in the UI thread and delivers
             * the result from doInBackground() */
            @Override
            protected void onPostExecute(Uri fileURI) {
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, fileURI);
                shareIntent.setType("application/zip");
                startActivity(Intent.createChooser(shareIntent, "Send Scan To..."));
                mWaitingLinearLayout.setVisibility(View.GONE);
            }
        }
        new SendCommandTask().execute(this);

    }
    mutex_on_mIsRecording.release();

}

From source file:com.keylesspalace.tusky.ComposeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    String theme = preferences.getString("appTheme", ThemeUtils.APP_THEME_DEFAULT);
    if (theme.equals("black")) {
        setTheme(R.style.TuskyDialogActivityBlackTheme);
    }/* www  . j  a va  2 s .c  o  m*/
    setContentView(R.layout.activity_compose);

    replyTextView = findViewById(R.id.composeReplyView);
    replyContentTextView = findViewById(R.id.composeReplyContentView);
    textEditor = findViewById(R.id.composeEditField);
    mediaPreviewBar = findViewById(R.id.compose_media_preview_bar);
    contentWarningBar = findViewById(R.id.composeContentWarningBar);
    contentWarningEditor = findViewById(R.id.composeContentWarningField);
    charactersLeft = findViewById(R.id.composeCharactersLeftView);
    tootButton = findViewById(R.id.composeTootButton);
    pickButton = findViewById(R.id.composeAddMediaButton);
    visibilityButton = findViewById(R.id.composeToggleVisibilityButton);
    contentWarningButton = findViewById(R.id.composeContentWarningButton);
    emojiButton = findViewById(R.id.composeEmojiButton);
    hideMediaToggle = findViewById(R.id.composeHideMediaButton);
    emojiView = findViewById(R.id.emojiView);
    emojiList = Collections.emptyList();

    saveTootHelper = new SaveTootHelper(database.tootDao(), this);

    // Setup the toolbar.
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(null);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp);
        ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint);
        actionBar.setHomeAsUpIndicator(closeIcon);
    }

    // setup the account image
    final AccountEntity activeAccount = accountManager.getActiveAccount();

    if (activeAccount != null) {
        ImageView composeAvatar = findViewById(R.id.composeAvatar);

        if (TextUtils.isEmpty(activeAccount.getProfilePictureUrl())) {
            composeAvatar.setImageResource(R.drawable.avatar_default);
        } else {
            Picasso.with(this).load(activeAccount.getProfilePictureUrl()).error(R.drawable.avatar_default)
                    .placeholder(R.drawable.avatar_default).into(composeAvatar);
        }

        composeAvatar.setContentDescription(
                getString(R.string.compose_active_account_description, activeAccount.getFullName()));

        mastodonApi.getInstance().enqueue(new Callback<Instance>() {
            @Override
            public void onResponse(@NonNull Call<Instance> call, @NonNull Response<Instance> response) {
                if (response.isSuccessful() && response.body().getMaxTootChars() != null) {
                    maximumTootCharacters = response.body().getMaxTootChars();
                    updateVisibleCharactersLeft();
                    cacheInstanceMetadata(activeAccount);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Instance> call, @NonNull Throwable t) {
                Log.w(TAG, "error loading instance data", t);
                loadCachedInstanceMetadata(activeAccount);
            }
        });

        mastodonApi.getCustomEmojis().enqueue(new Callback<List<Emoji>>() {
            @Override
            public void onResponse(@NonNull Call<List<Emoji>> call, @NonNull Response<List<Emoji>> response) {
                emojiList = response.body();
                setEmojiList(emojiList);
                cacheInstanceMetadata(activeAccount);
            }

            @Override
            public void onFailure(@NonNull Call<List<Emoji>> call, @NonNull Throwable t) {
                Log.w(TAG, "error loading custom emojis", t);
                loadCachedInstanceMetadata(activeAccount);
            }
        });
    } else {
        // do not do anything when not logged in, activity will be finished in super.onCreate() anyway
        return;
    }

    composeOptionsView = findViewById(R.id.composeOptionsBottomSheet);
    composeOptionsView.setListener(this);

    composeOptionsBehavior = BottomSheetBehavior.from(composeOptionsView);
    composeOptionsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

    addMediaBehavior = BottomSheetBehavior.from(findViewById(R.id.addMediaBottomSheet));

    emojiBehavior = BottomSheetBehavior.from(emojiView);

    emojiView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.HORIZONTAL, false));

    enableButton(emojiButton, false, false);

    // Setup the interface buttons.
    tootButton.setOnClickListener(v -> onSendClicked());
    pickButton.setOnClickListener(v -> openPickDialog());
    visibilityButton.setOnClickListener(v -> showComposeOptions());
    contentWarningButton.setOnClickListener(v -> onContentWarningChanged());
    emojiButton.setOnClickListener(v -> showEmojis());
    hideMediaToggle.setOnClickListener(v -> toggleHideMedia());

    TextView actionPhotoTake = findViewById(R.id.action_photo_take);
    TextView actionPhotoPick = findViewById(R.id.action_photo_pick);

    int textColor = ThemeUtils.getColor(this, android.R.attr.textColorTertiary);

    Drawable cameraIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_alt).color(textColor)
            .sizeDp(18);
    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoTake, cameraIcon, null, null,
            null);

    Drawable imageIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_image).color(textColor).sizeDp(18);
    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoPick, imageIcon, null, null,
            null);

    actionPhotoTake.setOnClickListener(v -> initiateCameraApp());
    actionPhotoPick.setOnClickListener(v -> onMediaPick());

    thumbnailViewSize = getResources().getDimensionPixelSize(R.dimen.compose_media_preview_size);

    /* Initialise all the state, or restore it from a previous run, to determine a "starting"
     * state. */
    Status.Visibility startingVisibility = Status.Visibility.UNKNOWN;
    boolean startingHideText;
    ArrayList<SavedQueuedMedia> savedMediaQueued = null;
    if (savedInstanceState != null) {
        startingVisibility = Status.Visibility
                .byNum(savedInstanceState.getInt("statusVisibility", Status.Visibility.PUBLIC.getNum()));
        statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive");
        startingHideText = savedInstanceState.getBoolean("statusHideText");
        // Keep these until everything needed to put them in the queue is finished initializing.
        savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued");
        // These are for restoring an in-progress commit content operation.
        InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat
                .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo"));
        int previousFlags = savedInstanceState.getInt("commitContentFlags");
        if (previousInputContentInfo != null) {
            onCommitContentInternal(previousInputContentInfo, previousFlags);
        }
        photoUploadUri = savedInstanceState.getParcelable("photoUploadUri");
    } else {
        statusMarkSensitive = false;
        startingHideText = false;
        photoUploadUri = null;
    }

    /* If the composer is started up as a reply to another post, override the "starting" state
     * based on what the intent from the reply request passes. */
    Intent intent = getIntent();

    String[] mentionedUsernames = null;
    ArrayList<String> loadedDraftMediaUris = null;
    inReplyToId = null;
    if (intent != null) {

        if (startingVisibility == Status.Visibility.UNKNOWN) {
            Status.Visibility preferredVisibility = Status.Visibility.byString(
                    preferences.getString("defaultPostPrivacy", Status.Visibility.PUBLIC.serverString()));
            Status.Visibility replyVisibility = Status.Visibility
                    .byNum(intent.getIntExtra(REPLY_VISIBILITY_EXTRA, Status.Visibility.UNKNOWN.getNum()));

            startingVisibility = Status.Visibility
                    .byNum(Math.max(preferredVisibility.getNum(), replyVisibility.getNum()));
        }

        inReplyToId = intent.getStringExtra(IN_REPLY_TO_ID_EXTRA);

        mentionedUsernames = intent.getStringArrayExtra(MENTIONED_USERNAMES_EXTRA);

        String contentWarning = intent.getStringExtra(CONTENT_WARNING_EXTRA);
        if (contentWarning != null) {
            startingHideText = !contentWarning.isEmpty();
            if (startingHideText) {
                startingContentWarning = contentWarning;
            }
        }

        // If come from SavedTootActivity
        String savedTootText = intent.getStringExtra(SAVED_TOOT_TEXT_EXTRA);
        if (!TextUtils.isEmpty(savedTootText)) {
            startingText = savedTootText;
            textEditor.setText(savedTootText);
        }

        String savedJsonUrls = intent.getStringExtra(SAVED_JSON_URLS_EXTRA);
        if (!TextUtils.isEmpty(savedJsonUrls)) {
            // try to redo a list of media
            loadedDraftMediaUris = new Gson().fromJson(savedJsonUrls, new TypeToken<ArrayList<String>>() {
            }.getType());
        }

        int savedTootUid = intent.getIntExtra(SAVED_TOOT_UID_EXTRA, 0);
        if (savedTootUid != 0) {
            this.savedTootUid = savedTootUid;
        }

        if (intent.hasExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA)) {
            replyTextView.setVisibility(View.VISIBLE);
            String username = intent.getStringExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA);
            replyTextView.setText(getString(R.string.replying_to, username));
            Drawable arrowDownIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_down)
                    .sizeDp(12);

            ThemeUtils.setDrawableTint(this, arrowDownIcon, android.R.attr.textColorTertiary);
            TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                    arrowDownIcon, null);

            replyTextView.setOnClickListener(v -> {
                TransitionManager.beginDelayedTransition((ViewGroup) replyContentTextView.getParent());

                if (replyContentTextView.getVisibility() != View.VISIBLE) {
                    replyContentTextView.setVisibility(View.VISIBLE);
                    Drawable arrowUpIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_up)
                            .sizeDp(12);

                    ThemeUtils.setDrawableTint(this, arrowUpIcon, android.R.attr.textColorTertiary);
                    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                            arrowUpIcon, null);
                } else {
                    replyContentTextView.setVisibility(View.GONE);

                    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                            arrowDownIcon, null);
                }
            });
        }

        if (intent.hasExtra(REPLYING_STATUS_CONTENT_EXTRA)) {
            replyContentTextView.setText(intent.getStringExtra(REPLYING_STATUS_CONTENT_EXTRA));
        }
    }

    // After the starting state is finalised, the interface can be set to reflect this state.
    setStatusVisibility(startingVisibility);

    updateHideMediaToggle();
    updateVisibleCharactersLeft();

    // Setup the main text field.
    textEditor.setOnCommitContentListener(this);
    final int mentionColour = textEditor.getLinkTextColors().getDefaultColor();
    SpanUtilsKt.highlightSpans(textEditor.getText(), mentionColour);
    textEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            SpanUtilsKt.highlightSpans(editable, mentionColour);
            updateVisibleCharactersLeft();
        }
    });

    textEditor.setAdapter(new MentionAutoCompleteAdapter(this, R.layout.item_autocomplete, this));
    textEditor.setTokenizer(new MentionTokenizer());

    // Add any mentions to the text field when a reply is first composed.
    if (mentionedUsernames != null) {
        StringBuilder builder = new StringBuilder();
        for (String name : mentionedUsernames) {
            builder.append('@');
            builder.append(name);
            builder.append(' ');
        }
        startingText = builder.toString();
        textEditor.setText(startingText);
        textEditor.setSelection(textEditor.length());
    }

    // work around Android platform bug -> https://issuetracker.google.com/issues/67102093
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
        textEditor.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // Initialise the content warning editor.
    contentWarningEditor.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) {
            updateVisibleCharactersLeft();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    showContentWarning(startingHideText);
    if (startingContentWarning != null) {
        contentWarningEditor.setText(startingContentWarning);
    }

    // Initialise the empty media queue state.
    waitForMediaLatch = new CountUpDownLatch();

    // These can only be added after everything affected by the media queue is initialized.
    if (!ListUtils.isEmpty(loadedDraftMediaUris)) {
        for (String uriString : loadedDraftMediaUris) {
            Uri uri = Uri.parse(uriString);
            long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri);
            pickMedia(uri, mediaSize);
        }
    } else if (savedMediaQueued != null) {
        for (SavedQueuedMedia item : savedMediaQueued) {
            Bitmap preview = MediaUtils.getImageThumbnail(getContentResolver(), item.uri, thumbnailViewSize);
            addMediaToQueue(item.id, item.type, preview, item.uri, item.mediaSize, item.readyStage,
                    item.description);
        }
    } else if (intent != null && savedInstanceState == null) {
        /* Get incoming images being sent through a share action from another app. Only do this
         * when savedInstanceState is null, otherwise both the images from the intent and the
         * instance state will be re-queued. */
        String type = intent.getType();
        if (type != null) {
            if (type.startsWith("image/")) {
                List<Uri> uriList = new ArrayList<>();
                if (intent.getAction() != null) {
                    switch (intent.getAction()) {
                    case Intent.ACTION_SEND: {
                        Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                        if (uri != null) {
                            uriList.add(uri);
                        }
                        break;
                    }
                    case Intent.ACTION_SEND_MULTIPLE: {
                        ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                        if (list != null) {
                            for (Uri uri : list) {
                                if (uri != null) {
                                    uriList.add(uri);
                                }
                            }
                        }
                        break;
                    }
                    }
                }
                for (Uri uri : uriList) {
                    long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri);
                    pickMedia(uri, mediaSize);
                }
            } else if (type.equals("text/plain")) {
                String action = intent.getAction();
                if (action != null && action.equals(Intent.ACTION_SEND)) {
                    String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                    if (text != null) {
                        int start = Math.max(textEditor.getSelectionStart(), 0);
                        int end = Math.max(textEditor.getSelectionEnd(), 0);
                        int left = Math.min(start, end);
                        int right = Math.max(start, end);
                        textEditor.getText().replace(left, right, text, 0, text.length());
                    }
                }
            }
        }
    }

    textEditor.requestFocus();
}

From source file:info.tellmetime.TellmetimeActivity.java

@Override
public boolean onMenuItemClick(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
    case R.id.action_mode:
        if (!mSettings.contains(BACKGROUND_MODE_TOGGLED))
            showToast(R.string.info_toggle_mode);

        toggleMode();//w  w w. j  a va  2  s .co  m

        mHider.hide();
        return true;
    case R.id.action_share_screenshot:
        mHider.hideNow();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    View rootView = getWindow().getDecorView().getRootView();
                    rootView.setDrawingCacheEnabled(true);
                    Bitmap screenshot = Bitmap.createBitmap(rootView.getDrawingCache());
                    rootView.setDrawingCacheEnabled(false);

                    showToast(R.string.info_saving_screenshot);

                    ContentValues values = new ContentValues();
                    values.put(MediaStore.Images.Media.TITLE, getString(R.string.app_name));
                    values.put(MediaStore.Images.Media.DISPLAY_NAME, getString(R.string.app_name) + ".jpg");
                    values.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
                    Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                    OutputStream outputStream;
                    outputStream = getContentResolver().openOutputStream(uri);
                    screenshot.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    outputStream.close();
                    screenshot.recycle();

                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("image/jpeg");
                    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
                    String shareText = getString(R.string.app_description)
                            + " Get it at http://tellmetime.info";
                    intent.putExtra(Intent.EXTRA_TEXT, shareText);
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                    startActivity(Intent.createChooser(intent, "Share via"));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return true;
    case R.id.action_share_app:
        try {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
            String shareText = getString(R.string.app_description) + " Get it at http://tellmetime.info";
            intent.putExtra(Intent.EXTRA_TEXT, shareText);
            startActivity(Intent.createChooser(intent, "Share via"));
        } catch (Exception ignored) {
        }

        return true;
    case R.id.action_rate:
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=info.tellmetime"));
        startActivity(intent);

        return true;
    default:
        return false;
    }
}

From source file:com.zertinteractive.wallpaper.activities.DetailActivity.java

public void shareImage() {

    String path = Environment.getExternalStorageDirectory().toString();
    File file = new File(path, "/" + TEMP_WALLPAPER_DIR + "/" + TEMP_WALLPAPER_NAME + ".png");

    Uri imageUri = Uri.fromFile(file);//  w  w  w.jav  a 2  s .  c  om
    if (file.exists()) {
        ;
        Log.e("FILE - ", file.getAbsolutePath());
    } else {
        Log.e("ERROR - ", file.getAbsolutePath());
    }

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_TEXT, "Mood Wallpaper");
    intent.putExtra(Intent.EXTRA_STREAM, imageUri);
    intent.setType("image/*");
    startActivity(intent);
}