Example usage for android.content Intent ACTION_OPEN_DOCUMENT

List of usage examples for android.content Intent ACTION_OPEN_DOCUMENT

Introduction

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

Prototype

String ACTION_OPEN_DOCUMENT

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

Click Source Link

Document

Activity Action: Allow the user to select and return one or more existing documents.

Usage

From source file:org.inframiner.firebase.starter.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    // Set default username is anonymous.
    mUsername = ANONYMOUS;// w  w w  .j av a2  s  . c om

    // Initialize Firebase Auth
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseUser = mFirebaseAuth.getCurrentUser();
    if (mFirebaseUser == null) {
        // Not signed in, launch the Sign In activity
        startActivity(new Intent(this, SignInActivity.class));
        finish();
        return;
    } else {
        mUsername = mFirebaseUser.getDisplayName();
        if (mFirebaseUser.getPhotoUrl() != null) {
            mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
        }
    }

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API).addApi(AppInvite.API).build();

    // Initialize ProgressBar and RecyclerView.
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(this);
    mLinearLayoutManager.setStackFromEnd(true);

    mProgressBar.setVisibility(ProgressBar.INVISIBLE);

    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
            mSharedPreferences.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT)) });
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mSendButton = (Button) findViewById(R.id.sendButton);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Send messages on click.
            FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(),
                    mUsername, mPhotoUrl, null /* no image */);
            mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(friendlyMessage);
            mMessageEditText.setText("");
        }
    });

    mAddMessageImageView = (ImageView) findViewById(R.id.addMessageImageView);
    mAddMessageImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Select image for image message on click.
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_IMAGE);
        }
    });

    // New child entries
    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
    mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(FriendlyMessage.class,
            R.layout.item_message, MessageViewHolder.class, mFirebaseDatabaseReference.child(MESSAGES_CHILD)) {

        @Override
        protected FriendlyMessage parseSnapshot(DataSnapshot snapshot) {
            //                return super.parseSnapshot(snapshot);
            FriendlyMessage friendlyMessage = super.parseSnapshot(snapshot);
            if (friendlyMessage != null) {
                friendlyMessage.setId(snapshot.getKey());
            }
            return friendlyMessage;
        }

        @Override
        protected void populateViewHolder(final MessageViewHolder viewHolder, FriendlyMessage friendlyMessage,
                int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            if (friendlyMessage.getText() != null) {
                viewHolder.messageTextView.setText(friendlyMessage.getText());
                viewHolder.messageTextView.setVisibility(TextView.VISIBLE);
                viewHolder.messageImageView.setVisibility(ImageView.GONE);
            } else {
                String imageUrl = friendlyMessage.getImageUrl();
                if (imageUrl.startsWith("gs://")) {
                    StorageReference storageReference = FirebaseStorage.getInstance()
                            .getReferenceFromUrl(imageUrl);
                    storageReference.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                        @Override
                        public void onComplete(@NonNull Task<Uri> task) {
                            if (task.isSuccessful()) {
                                String downloadUrl = task.getResult().toString();
                                Glide.with(viewHolder.messageImageView.getContext()).load(downloadUrl)
                                        .into(viewHolder.messageImageView);
                            } else {
                                Log.w(TAG, "Getting download url was not successful", task.getException());
                            }
                        }
                    });
                } else {
                    Glide.with(viewHolder.messageImageView.getContext()).load(friendlyMessage.getImageUrl())
                            .into(viewHolder.messageImageView);
                }
                viewHolder.messageImageView.setVisibility(ImageView.VISIBLE);
                viewHolder.messageTextView.setVisibility(TextView.GONE);
            }

            viewHolder.messengerTextView.setText(friendlyMessage.getName());
            if (friendlyMessage.getPhotoUrl() == null) {
                viewHolder.messengerImageView.setImageDrawable(
                        ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_account_circle_black_36dp));
            } else {
                Glide.with(MainActivity.this).load(friendlyMessage.getPhotoUrl())
                        .into(viewHolder.messengerImageView);
            }

            // write this message to the on-device index
            if (friendlyMessage.getText() != null) {
                FirebaseAppIndex.getInstance().update(getMessageIndexable(friendlyMessage));
            }

            // log a view action on it
            FirebaseUserActions.getInstance().end(getMessageViewAction(friendlyMessage));
        }
    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();

            // If the recycler view is initially being loaded or the
            // user is at the bottom of the list, scroll to the bottom
            // of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    // Initialize Firebase Remote Config.
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

    // Define Firebase Remote Config Settings.
    FirebaseRemoteConfigSettings firebaseRemoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
            .setDeveloperModeEnabled(true).build();

    // Define default config values. Defaults are used when fetched config values are not
    // available. Eg: if an error occurred fetching values from the server.
    Map<String, Object> defaultConfigMap = new HashMap<>();
    defaultConfigMap.put("friendly_msg_length", 10L);

    // Apply config settings and default values.
    mFirebaseRemoteConfig.setConfigSettings(firebaseRemoteConfigSettings);
    mFirebaseRemoteConfig.setDefaults(defaultConfigMap);

    // Fetch remote config.
    fetchConfig();

    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
}

From source file:com.android.documentsui.DocumentsActivity.java

private void buildDefaultState() {
    mState = new State();

    final Intent intent = getIntent();
    final String action = intent.getAction();
    if (Intent.ACTION_OPEN_DOCUMENT.equals(action)) {
        mState.action = ACTION_OPEN;/* www . j a v  a  2 s  .  c  o  m*/
    } else if (Intent.ACTION_CREATE_DOCUMENT.equals(action)) {
        mState.action = ACTION_CREATE;
    } else if (Intent.ACTION_GET_CONTENT.equals(action)) {
        mState.action = ACTION_GET_CONTENT;
    } else if (DocumentsContract.ACTION_MANAGE_ROOT.equals(action)) {
        mState.action = ACTION_MANAGE;
    }

    if (mState.action == ACTION_OPEN || mState.action == ACTION_GET_CONTENT) {
        mState.allowMultiple = intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
    }

    if (mState.action == ACTION_MANAGE) {
        mState.acceptMimes = new String[] { "*/*" };
        mState.allowMultiple = true;
    } else if (intent.hasExtra(Intent.EXTRA_MIME_TYPES)) {
        mState.acceptMimes = intent.getStringArrayExtra(Intent.EXTRA_MIME_TYPES);
    } else {
        mState.acceptMimes = new String[] { intent.getType() };
    }

    mState.localOnly = intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false);
    mState.forceAdvanced = intent.getBooleanExtra(DocumentsContract.EXTRA_SHOW_ADVANCED, false);
    mState.showAdvanced = mState.forceAdvanced | SettingsActivity.getDisplayAdvancedDevices(this);
}

From source file:cn.edu.wyu.documentviewer.DocumentsActivity.java

private void buildDefaultState() {
    mState = new State();

    final Intent intent = virtualIntent;
    final String action = intent.getAction();
    if (Intent.ACTION_OPEN_DOCUMENT.equals(action)) {
        mState.action = ACTION_OPEN;/*from  ww  w . j a v a  2s .co  m*/
    } else if (Intent.ACTION_CREATE_DOCUMENT.equals(action)) {
        mState.action = ACTION_CREATE;
    } else if (Intent.ACTION_GET_CONTENT.equals(action)) {
        mState.action = ACTION_GET_CONTENT;
    } else if (DocumentsContract.ACTION_MANAGE_ROOT.equals(action)) {
        mState.action = ACTION_MANAGE;
    }

    if (mState.action == ACTION_OPEN || mState.action == ACTION_GET_CONTENT) {
        mState.allowMultiple = intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
    }

    if (mState.action == ACTION_MANAGE) {
        mState.acceptMimes = new String[] { "*/*" };
        mState.allowMultiple = true;
    } else if (intent.hasExtra(Intent.EXTRA_MIME_TYPES)) {
        mState.acceptMimes = intent.getStringArrayExtra(Intent.EXTRA_MIME_TYPES);
    } else {
        mState.acceptMimes = new String[] { intent.getType() };
    }

    mState.localOnly = intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false);
    mState.forceAdvanced = intent.getBooleanExtra(DocumentsContract.EXTRA_SHOW_ADVANCED, false);
    mState.showAdvanced = mState.forceAdvanced | SettingsActivity.getDisplayAdvancedDevices(this);
}

From source file:com.farmerbb.notepad.fragment.NoteListFragment.java

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override/*ww  w  .  j a  v  a2 s  .  c o m*/
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
    case R.id.action_start_selection:
        listener.startMultiSelect();
        return true;
    case R.id.action_settings:
        Intent intentSettings = new Intent(getActivity(), SettingsActivity.class);
        startActivity(intentSettings);
        return true;
    case R.id.action_import:
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] { "text/plain", "text/html", "text/x-markdown" });
        intent.setType("*/*");

        try {
            getActivity().startActivityForResult(intent, MainActivity.IMPORT);
        } catch (ActivityNotFoundException e) {
            showToast(R.string.error_importing_notes);
        }
        return true;
    case R.id.action_about:
        DialogFragment aboutFragment = new AboutDialogFragment();
        aboutFragment.show(getFragmentManager(), "about");
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.google.android.apps.muzei.gallery.GallerySettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_activity);
    Toolbar appBar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(appBar);/*w  w  w.  java2s  . com*/

    getSupportLoaderManager().initLoader(0, null, this);

    bindService(new Intent(this, GalleryArtSource.class).setAction(GalleryArtSource.ACTION_BIND_GALLERY),
            mServiceConnection, BIND_AUTO_CREATE);

    mPlaceholderDrawable = new ColorDrawable(
            ContextCompat.getColor(this, R.color.gallery_chosen_photo_placeholder));

    mPhotoGridView = (RecyclerView) findViewById(R.id.photo_grid);
    DefaultItemAnimator itemAnimator = new DefaultItemAnimator();
    itemAnimator.setSupportsChangeAnimations(false);
    mPhotoGridView.setItemAnimator(itemAnimator);
    setupMultiSelect();

    final GridLayoutManager gridLayoutManager = new GridLayoutManager(GallerySettingsActivity.this, 1);
    mPhotoGridView.setLayoutManager(gridLayoutManager);

    final ViewTreeObserver vto = mPhotoGridView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int width = mPhotoGridView.getWidth() - mPhotoGridView.getPaddingStart()
                    - mPhotoGridView.getPaddingEnd();
            if (width <= 0) {
                return;
            }

            // Compute number of columns
            int maxItemWidth = getResources()
                    .getDimensionPixelSize(R.dimen.gallery_chosen_photo_grid_max_item_size);
            int numColumns = 1;
            while (true) {
                if (width / numColumns > maxItemWidth) {
                    ++numColumns;
                } else {
                    break;
                }
            }

            int spacing = getResources().getDimensionPixelSize(R.dimen.gallery_chosen_photo_grid_spacing);
            mItemSize = (width - spacing * (numColumns - 1)) / numColumns;

            // Complete setup
            gridLayoutManager.setSpanCount(numColumns);
            mChosenPhotosAdapter.setHasStableIds(true);
            mPhotoGridView.setAdapter(mChosenPhotosAdapter);

            mPhotoGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            tryUpdateSelection(false);
        }
    });

    ViewCompat.setOnApplyWindowInsetsListener(mPhotoGridView, new OnApplyWindowInsetsListener() {
        @Override
        public WindowInsetsCompat onApplyWindowInsets(final View v, final WindowInsetsCompat insets) {
            int gridSpacing = getResources().getDimensionPixelSize(R.dimen.gallery_chosen_photo_grid_spacing);
            ViewCompat.onApplyWindowInsets(v,
                    insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft() + gridSpacing,
                            gridSpacing, insets.getSystemWindowInsetRight() + gridSpacing,
                            insets.getSystemWindowInsetBottom() + insets.getSystemWindowInsetTop() + gridSpacing
                                    + getResources().getDimensionPixelSize(R.dimen.gallery_fab_space)));

            return insets;
        }
    });

    Button enableRandomImages = (Button) findViewById(R.id.gallery_enable_random);
    enableRandomImages.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            ActivityCompat.requestPermissions(GallerySettingsActivity.this,
                    new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, REQUEST_STORAGE_PERMISSION);
        }
    });
    Button permissionSettings = (Button) findViewById(R.id.gallery_edit_permission_settings);
    permissionSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                    Uri.fromParts("package", getPackageName(), null));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    });
    mAddButton = findViewById(R.id.add_photos_button);
    mAddButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Use ACTION_OPEN_DOCUMENT by default for adding photos.
            // This allows us to use persistent URI permissions to access the underlying photos
            // meaning we don't need to use additional storage space and will pull in edits automatically
            // in addition to syncing deletions.
            // (There's a separate 'Import photos' option which uses ACTION_GET_CONTENT to support legacy apps)
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            startActivityForResult(intent, REQUEST_CHOOSE_PHOTOS);
        }
    });
}

From source file:com.snappy.CameraCropActivity.java

private void getImageIntents() {
    /*/* ww w.j  a  va 2s.co m*/
     * if (getIntent().hasExtra("trio")) { _trio = true; _groupId =
     * getIntent().getStringExtra("groupId"); _planner =
     * getIntent().getBooleanExtra("planner", false); } else { _trio =
     * false; _planner = false; _groupId = ""; }
     */
    if (getIntent().getStringExtra("type").equals("gallery")) {

        //this is used to solve the selected path for android 19, kitkat o superior
        if (Build.VERSION.SDK_INT < 19) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            this.startActivityForResult(intent, GALLERY);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            this.startActivityForResult(intent, GALLERY);
        }

        mIsCamera = false;

    } else {
        try {
            startCamera();
            mIsCamera = true;
        } catch (UnsupportedOperationException ex) {
            ex.printStackTrace();
            Toast.makeText(getBaseContext(), "UnsupportedOperationException", Toast.LENGTH_SHORT).show();
        }
    }
    if (getIntent().getBooleanExtra("profile", false) == true) {
        mForProfile = true;
    } else {
        mForProfile = false;
    }
    if (getIntent().getBooleanExtra("createGroup", false) == true) {
        mForGroup = true;
    } else {
        mForGroup = false;
    }
    if (getIntent().getBooleanExtra("groupUpdate", false) == true) {
        mForGroupUpdate = true;
    } else {
        mForGroupUpdate = false;
    }
}

From source file:com.kdao.cmpe235_project.UploadActivity.java

private void initUI() {
    /**// w  ww  .  j  a  v  a  2s . co m
     * This adapter takes the data in transferRecordMaps and displays it,
     * with the keys of the map being related to the columns in the adapter
     */
    simpleAdapter = new SimpleAdapter(this, transferRecordMaps, R.layout.record_item,
            new String[] { "checked", "fileName", "progress", "bytes", "state", "percentage" },
            new int[] { R.id.radioButton1, R.id.textFileName, R.id.progressBar1, R.id.textBytes, R.id.textState,
                    R.id.textPercentage });
    simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Object data, String textRepresentation) {
            switch (view.getId()) {
            case R.id.radioButton1:
                RadioButton radio = (RadioButton) view;
                radio.setChecked((Boolean) data);
                return true;
            case R.id.textFileName:
                TextView fileName = (TextView) view;
                fileName.setText((String) data);
                return true;
            case R.id.progressBar1:
                ProgressBar progress = (ProgressBar) view;
                progress.setProgress((Integer) data);
                return true;
            case R.id.textBytes:
                TextView bytes = (TextView) view;
                bytes.setText((String) data);
                return true;
            case R.id.textState:
                TextView state = (TextView) view;
                state.setText(((TransferState) data).toString());
                return true;
            case R.id.textPercentage:
                TextView percentage = (TextView) view;
                percentage.setText((String) data);
                return true;
            }
            return false;
        }
    });
    setListAdapter(simpleAdapter);

    // Updates checked index when an item is clicked
    getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {

            if (checkedIndex != pos) {
                transferRecordMaps.get(pos).put("checked", true);
                if (checkedIndex >= 0) {
                    transferRecordMaps.get(checkedIndex).put("checked", false);
                }
                checkedIndex = pos;
                updateButtonAvailability();
                simpleAdapter.notifyDataSetChanged();
            }
        }
    });

    //btnUploadFile = (Button) findViewById(R.id.buttonUploadFile);
    btnUploadImage = (Button) findViewById(R.id.buttonUploadImage);
    btnUploadAudio = (Button) findViewById(R.id.buttonUploadAudio);
    btnUploadVideo = (Button) findViewById(R.id.buttonUploadVideo);
    btnPause = (Button) findViewById(R.id.buttonPause);
    btnResume = (Button) findViewById(R.id.buttonResume);
    btnCancel = (Button) findViewById(R.id.buttonCancel);
    btnDelete = (Button) findViewById(R.id.buttonDelete);
    btnPauseAll = (Button) findViewById(R.id.buttonPauseAll);
    btnCancelAll = (Button) findViewById(R.id.buttonCancelAll);

    btnUploadImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isTreeSelected) {
                System.out.println(">>>>> Start uploading photos... <<<<<<<");
                Intent intent = new Intent();
                if (Build.VERSION.SDK_INT >= 19) {
                    // For Android versions of KitKat or later, we use a
                    // different intent to ensure
                    // we can get the file path from the returned intent URI
                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
                } else {
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                APIurl = "/tree/" + treeId + "/photo";
                intent.setType("image/*");
                startActivityForResult(intent, 0);
            } else {
                Toast.makeText(getApplicationContext(), Config.UPLOAD_NOTREE_ERR, Toast.LENGTH_LONG).show();
            }
        }
    });

    btnUploadAudio.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isTreeSelected) {
                Intent intent = new Intent();
                if (Build.VERSION.SDK_INT >= 19) {
                    // For Android versions of KitKat or later, we use a
                    // different intent to ensure
                    // we can get the file path from the returned intent URI
                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
                } else {
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                APIurl = "/tree/" + treeId + "/audio";
                intent.setType("audio/*");
                startActivityForResult(intent, 0);
            } else {
                Toast.makeText(getApplicationContext(), Config.UPLOAD_NOTREE_ERR, Toast.LENGTH_LONG).show();
            }
        }

    });

    btnUploadVideo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isTreeSelected) {
                Intent intent = new Intent();
                if (Build.VERSION.SDK_INT >= 19) {
                    // For Android versions of KitKat or later, we use a
                    // different intent to ensure
                    // we can get the file path from the returned intent URI
                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
                } else {
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                APIurl = "/tree/" + treeId + "/video";
                intent.setType("video/*");
                startActivityForResult(intent, 0);
            } else {
                Toast.makeText(getApplicationContext(), Config.UPLOAD_NOTREE_ERR, Toast.LENGTH_LONG).show();
            }
        }
    });

    btnPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Make sure the user has selected a transfer
            if (checkedIndex >= 0 && checkedIndex < observers.size()) {
                Boolean paused = transferUtility.pause(observers.get(checkedIndex).getId());
                /**
                 * If paused does not return true, it is likely because the
                 * user is trying to pause an upload that is not in a
                 * pausable state (For instance it is already paused, or
                 * canceled).
                 */
                if (!paused) {
                    Toast.makeText(UploadActivity.this, Config.UPLOAD_PAUSE_ERR, Toast.LENGTH_SHORT).show();
                }
            }
        }
    });

    btnResume.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Make sure the user has selected a transfer
            if (checkedIndex >= 0 && checkedIndex < observers.size()) {
                TransferObserver resumed = transferUtility.resume(observers.get(checkedIndex).getId());
                // Sets a new transfer listener to the original observer.
                // This will overwrite existing listener.
                observers.get(checkedIndex).setTransferListener(new UploadListener());
                /**
                 * If resume returns null, it is likely because the transfer
                 * is not in a resumable state (For instance it is already
                 * running).
                 */
                if (resumed == null) {
                    Toast.makeText(UploadActivity.this, Config.UPLOAD_RESUME_ERR, Toast.LENGTH_SHORT).show();
                }
            }
        }
    });

    btnCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Make sure a transfer is selected
            if (checkedIndex >= 0 && checkedIndex < observers.size()) {
                Boolean canceled = transferUtility.cancel(observers.get(checkedIndex).getId());
                /**
                 * If cancel returns false, it is likely because the
                 * transfer is already canceled
                 */
                if (!canceled) {
                    Toast.makeText(UploadActivity.this, Config.UPLOAD_TRANSFER_ERR, Toast.LENGTH_SHORT).show();
                }
            }
        }
    });

    btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Make sure a transfer is selected
            if (checkedIndex >= 0 && checkedIndex < observers.size()) {
                transferUtility.deleteTransferRecord(observers.get(checkedIndex).getId());
                observers.remove(checkedIndex);
                transferRecordMaps.remove(checkedIndex);
                checkedIndex = INDEX_NOT_CHECKED;
                updateButtonAvailability();
                updateList();
            }
        }
    });

    btnPauseAll.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            transferUtility.pauseAllWithType(TransferType.UPLOAD);
        }
    });

    btnCancelAll.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            transferUtility.cancelAllWithType(TransferType.UPLOAD);
        }
    });

    updateButtonAvailability();
}

From source file:com.HumanDecisionSupportSystemsLaboratory.DD_P2P.Main.java

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override/*from   w ww  .ja  v  a 2s  .c om*/
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == R.id.add_new_safe_my) {
        try {
            DD.load_listing_directories();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this.getApplicationContext(), "Error: " + e.getLocalizedMessage(), Toast.LENGTH_LONG)
                    .show();
            // return;
        }

        if ((Identity.getListing_directories_addr().size() <= 0)) {
            Toast.makeText(this,
                    "To add your safe, first add a directory from the Manage Directories top-right menu!",
                    Toast.LENGTH_LONG).show();
            return super.onOptionsItemSelected(item);
        }
        Toast.makeText(this, "add a new safe my", Toast.LENGTH_SHORT).show();

        Intent intent = new Intent();
        intent.setClass(this, AddSafe.class);
        startActivityForResult(intent, Main.RESULT_ADD_PEER);
    }

    if (item.getItemId() == R.id.add_new_safe_other) {
        if ((Identity.getListing_directories_addr().size() <= 0)) {
            Toast.makeText(this,
                    "To add a safe, first add a directory from the Manage Directories top-right menu!",
                    Toast.LENGTH_LONG).show();
            return super.onOptionsItemSelected(item);
        }
        Toast.makeText(this, "add a new safe other", Toast.LENGTH_SHORT).show();

        if (Build.VERSION.SDK_INT < 19) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, SELECT_PHOTO);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.setType("image/*");
            startActivityForResult(intent, SELECT_PHOTO_KITKAT);
        }
    }

    if (item.getItemId() == R.id.add_new_org) {
        Toast.makeText(this, "add a new organization", Toast.LENGTH_SHORT).show();

        Intent intent = new Intent();
        intent.setClass(this, AddOrg.class);
        startActivity(intent);
    }

    if (item.getItemId() == R.id.action_directories) {
        Toast.makeText(this, "adding a directory", Toast.LENGTH_SHORT).show();

        Intent intent = new Intent();
        intent.setClass(this, SelectDirectoryServer.class);
        startActivity(intent);
    }

    if (item.getItemId() == R.id.action_loadAddresss) {

        FragmentManager fm = getSupportFragmentManager();
        LoadPK loadPKDialog = new LoadPK();
        loadPKDialog.show(fm, "fragment_send_public_key");

    }

    // not yet implemented!
    if (item.getItemId() == R.id.action_start_directory) {

        Intent i = new Intent();
        i.setClass(this, StartDirectoryServer.class);
        startActivity(i);
    }

    if (item.getItemId() == R.id.action_settings) {
        Intent intent = new Intent();
        intent.setClass(this, Setting.class);
        startActivity(intent);
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.awrtechnologies.carbudgetsales.MainActivity.java

public void imageOpen(Fragment f, final int REQUEST_CAMERA, final int SELECT_FILE) {

    GeneralHelper.getInstance(MainActivity.this).setTempFragment(f);
    final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {

        @Override//from ww  w  .ja  va2 s . c o  m
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {

                java.io.File imageFile = new File(
                        (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/."
                                + Constants.APPNAME + "/" + System.currentTimeMillis() + ".jpeg"));

                PreferencesManager.setPreferenceByKey(MainActivity.this, "IMAGEWWC",
                        imageFile.getAbsolutePath());
                //
                imageFilePath = imageFile;
                imageFileUri = Uri.fromFile(imageFile);
                Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
                startActivityForResult(i, REQUEST_CAMERA);

            } else if (items[item].equals("Choose from Library")) {
                if (Build.VERSION.SDK_INT < 19) {
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                } else {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                }

            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

From source file:jackpal.androidterm.TermPreferences.java

@SuppressLint("NewApi")
private void doPrefsPicker() {
    AlertDialog.Builder bld = new AlertDialog.Builder(this);
    bld.setIcon(android.R.drawable.ic_dialog_info);
    bld.setMessage(this.getString(R.string.prefs_dialog_rw));
    bld.setNeutralButton(this.getString(R.string.prefs_write), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();//from w ww . j  a  va 2 s  .  co m
            confirmWritePrefs();
        }
    });
    bld.setPositiveButton(this.getString(R.string.prefs_read), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("text/xml");
            startActivityForResult(intent, REQUEST_PREFS_READ_PICKER);
        }
    });
    bld.setNegativeButton(this.getString(android.R.string.no), null);
    bld.create().show();
}