public void setPrimaryClip(ClipData clip, String callingPackage) { synchronized (this) { if (clip != null && clip.getItemCount() <= 0) { throw new IllegalArgumentException("No items"); } final int callingUid = Binder.getCallingUid(); if (mAppOps.noteOp(AppOpsManager.OP_WRITE_CLIPBOARD, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) { return; } checkDataOwnerLocked(clip, callingUid); clearActiveOwnersLocked(); PerUserClipboard clipboard = getClipboard(); clipboard.primaryClip = clip; final long ident = Binder.clearCallingIdentity(); final int n = clipboard.primaryClipListeners.beginBroadcast(); try { for (int i = 0; i < n; i++) { try { ListenerInfo li = (ListenerInfo) clipboard.primaryClipListeners.getBroadcastCookie(i); if (mAppOps.checkOpNoThrow(AppOpsManager.OP_READ_CLIPBOARD, li.mUid, li.mPackageName) == AppOpsManager.MODE_ALLOWED) { clipboard.primaryClipListeners.getBroadcastItem(i).dispatchPrimaryClipChanged(); } } catch (RemoteException e) { // The RemoteCallbackList will take care of removing // the dead object for us. } } } finally { clipboard.primaryClipListeners.finishBroadcast(); Binder.restoreCallingIdentity(ident); } } }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == FILE_CODE && resultCode == Activity.RESULT_OK) { if (data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) { // For JellyBean and above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { ClipData clip = data.getClipData(); if (clip != null) { for (int i = 0; i < clip.getItemCount(); i++) { Uri uri = clip.getItemAt(i).getUri(); uploadFile(uri.getPath()); } } } else { ArrayList<String> paths = data.getStringArrayListExtra(FilePickerActivity.EXTRA_PATHS); if (paths != null) { for (String path : paths) { Uri uri = Uri.parse(path); uploadFile(uri.getPath()); } } } } else { Uri uri = data.getData(); uploadFile(uri.getPath()); } } }
private void processDrop(DragEvent event) { final ClipData data = event.getClipData(); final int N = data.getItemCount(); for (int i = 0; i < N; i++) { ClipData.Item item = data.getItemAt(i); String text = item.coerceToText(getContext()).toString(); if (this.tile.type.equalsIgnoreCase(Constants.BLANK)) { String[] tileArgs = text.split(";"); this.setTile( new Tile( this.tile.posOnBoard, tileArgs[1], Integer.parseInt(tileArgs[0]), MoveDirection.NONE, tileArgs[4], Constants.stringToBmp.get(tileArgs[1]))); Constants.droppedOnBlank = true; // Communicator.getInstance(null, // null).sendMoveTile(tileArgs[1]); ClientCommunicator.getInstance(getContext(), null).sendMoveRequset(tile); } else { Constants.droppedOnBlank = false; } } }
boolean processDrop(DragEvent event, ImageView imageView) { // Attempt to parse clip data with expected format: category||entry_id. // Ignore event if data does not conform to this format. ClipData data = event.getClipData(); if (data != null) { if (data.getItemCount() > 0) { Item item = data.getItemAt(0); String textData = (String) item.getText(); if (textData != null) { StringTokenizer tokenizer = new StringTokenizer(textData, "||"); if (tokenizer.countTokens() != 2) { return false; } int category = -1; int entryId = -1; try { category = Integer.parseInt(tokenizer.nextToken()); entryId = Integer.parseInt(tokenizer.nextToken()); } catch (NumberFormatException exception) { return false; } updateContentAndRecycleBitmap(category, entryId); // Update list fragment with selected entry. TitlesFragment titlesFrag = (TitlesFragment) getFragmentManager().findFragmentById(R.id.titles_frag); titlesFrag.selectPosition(entryId); return true; } } } return false; }
public boolean onActivityResult(final int requestCode, final int resultCode, final Intent data) { if (requestCode == ACTIVITY_FILE_CHOOSER) { choosing = false; if (resultCode == Activity.RESULT_OK) { Uri uri = data.getData(); if (uri != null) { // 單選 chosenFiles = getFilesFromUris(activity, new Uri[] {uri}, mustCanRead); return true; } else if (Build.VERSION.SDK_INT >= 16) { // 複選 ClipData clipData = data.getClipData(); if (clipData != null) { int count = clipData.getItemCount(); if (count > 0) { Uri[] uris = new Uri[count]; for (int i = 0; i < count; i++) { uris[i] = clipData.getItemAt(i).getUri(); } chosenFiles = getFilesFromUris(activity, uris, mustCanRead); return true; } } } } } return false; }
/** * 获取剪贴板的意图 * * @param context 上下文 * @return 剪贴板的意图 */ public static Intent getIntent(Context context) { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = clipboard.getPrimaryClip(); if (clip != null && clip.getItemCount() > 0) { return clip.getItemAt(0).getIntent(); } return null; }
private void pasteContent() { ClipData clip = getPrimaryClip(); if (clip != null) { for (int i = 0; i < clip.getItemCount(); i++) { CharSequence paste = clip.getItemAt(i).coerceToText(getContext()); if (canPaste(paste)) { ((Editable) getText()).insert(getSelectionEnd(), paste); } } } }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == IMAGE_GALLERY_RESULT && resultCode == RESULT_OK) { ClipData clip = data.getClipData(); if (clip != null) { for (int i = 0; i < clip.getItemCount(); i++) { Uri uri = clip.getItemAt(i).getUri(); Log.d(TAG, "File: " + uri.getPath()); } } } }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) public static String getImageUrl(final Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) return null; final ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); final ClipData primaryClip = cm.getPrimaryClip(); if (primaryClip.getItemCount() > 0) { final ClipData.Item item = primaryClip.getItemAt(0); final CharSequence styledText = item.coerceToStyledText(context); if (styledText instanceof Spanned) { final Spanned spanned = (Spanned) styledText; final ImageSpan[] imageSpans = spanned.getSpans(0, spanned.length(), ImageSpan.class); if (imageSpans.length == 1) return imageSpans[0].getSource(); } } return null; }
private void stash(ClipData clipping) { mClipping = clipping; if (mClipping != null) { setVisibility(View.VISIBLE); Bitmap icon = mClipping.getIcon(); // mDescription.setText(mClipping.getDescription().getLabel()); if (icon != null) { setImageBitmap(icon); } else { if (mClipping.getItemCount() > 0) { // TODO: figure out how to visualize every kind of ClipData! // mAltText.setText(mClipping.getItemAt(0).coerceToText(getContext())); } } } else { setVisibility(View.GONE); } }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 0 && resultCode == Activity.RESULT_OK) { if (data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { ClipData clip = data.getClipData(); StringBuilder sb = new StringBuilder(); if (clip != null) { for (int i = 0; i < clip.getItemCount(); i++) { sb.append(clip.getItemAt(i).getUri().toString()); sb.append("\n"); } } textView.setText(sb.toString()); } else { ArrayList<String> paths = data.getStringArrayListExtra(FilePickerActivity.EXTRA_PATHS); StringBuilder sb = new StringBuilder(); if (paths != null) { for (String path : paths) { sb.append(path); sb.append("\n"); } } textView.setText(sb.toString()); } } else { textView.setText(data.getData().toString()); } } }
@Override public void onCreateContextMenu(ContextMenu menu) { MenuHandler handler = new MenuHandler(); if (mMenuItemsStrings == null) { Resources resources = getResources(); mMenuItemsStrings = new String[3]; mMenuItemsStrings[CUT] = resources.getString(android.R.string.cut); mMenuItemsStrings[COPY] = resources.getString(android.R.string.copy); mMenuItemsStrings[PASTE] = resources.getString(android.R.string.paste); } for (int i = 0; i < mMenuItemsStrings.length; i++) { menu.add(Menu.NONE, i, i, mMenuItemsStrings[i]).setOnMenuItemClickListener(handler); } if (getText().length() == 0) { menu.getItem(CUT).setVisible(false); menu.getItem(COPY).setVisible(false); } ClipData primaryClip = getPrimaryClip(); if (primaryClip == null || primaryClip.getItemCount() == 0 || !canPaste(primaryClip.getItemAt(0).coerceToText(getContext()))) { menu.getItem(PASTE).setVisible(false); } }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case RequestCodes.TAKE_PHOTO: if (resultCode == Activity.RESULT_OK) { if (!FileUtil.isFileValid(mTempFile)) { Snackbar.make(mMultiView, R.string.upload_camera_error, Snackbar.LENGTH_LONG).show(); return; } FileUtil.scanFile(Uri.fromFile(mTempFile), getActivity()); String fileLocation = mTempFile.getAbsolutePath(); Upload upload = new Upload(fileLocation); if (mAdapter == null) { mAdapter = new UploadPhotoAdapter(getActivity(), upload, this); mRecyclerView.setAdapter(mAdapter); } else { mAdapter.addItem(upload); } mMultiView.setViewState(MultiStateView.VIEW_STATE_CONTENT); mTempFile = null; } break; case RequestCodes.SELECT_PHOTO: if (resultCode == Activity.RESULT_OK && data != null) { ClipData clipData = data.getClipData(); List<Uri> uris = null; // Check if we have multiple images if (clipData != null) { int size = clipData.getItemCount(); uris = new ArrayList<>(size); for (int i = 0; i < size; i++) { uris.add(clipData.getItemAt(i).getUri()); } } else if (data.getData() != null) { // If not multiple images, then only one was selected uris = new ArrayList<>(1); uris.add(data.getData()); } if (uris != null && !uris.isEmpty()) { mMultiView.setViewState(MultiStateView.VIEW_STATE_LOADING); new DecodeImagesTask(this).execute(uris); } else { Snackbar.make(mMultiView, R.string.error_generic, Snackbar.LENGTH_LONG).show(); } } break; case RequestCodes.UPLOAD_EDIT: if (resultCode == Activity.RESULT_OK && data != null) { final Upload upload; if (data.hasExtra(UploadEditActivity.KEY_UPDATED_UPLOAD)) { upload = data.getParcelableExtra(UploadEditActivity.KEY_UPDATED_UPLOAD); if (upload != null) { mAdapter.updateItem(upload); } } else if (data.hasExtra(UploadEditActivity.KEY_UPDATED_DELETED)) { upload = data.getParcelableExtra(UploadEditActivity.KEY_UPDATED_DELETED); if (upload != null) { final int itemIndex = mAdapter.indexOf(upload); if (itemIndex > -1) { mAdapter.removeItem(itemIndex); if (mListener != null) mListener.onPhotoRemoved(mAdapter.getItemCount()); if (mAdapter.isEmpty()) mMultiView.setViewState(MultiStateView.VIEW_STATE_EMPTY); Snackbar.make(mMultiView, R.string.upload_photo_removed, Snackbar.LENGTH_LONG) .setAction( R.string.undo, new View.OnClickListener() { @Override public void onClick(View v) { mMultiView.setViewState(MultiStateView.VIEW_STATE_CONTENT); mAdapter.addItem(upload, itemIndex); if (mListener != null) mListener.onPhotoAdded(); } }) .show(); } } } } break; } super.onActivityResult(requestCode, resultCode, data); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent resultIntent) { if (resultCode != RESULT_OK) { return; } switch (requestCode) { // 处理头像选择 case REQUEST_CODE_SELECT_AVATAR: Uri uri = null; if (resultIntent.getData() != null) { // 单选 uri = resultIntent.getData(); } else if (resultIntent.getClipData() != null) { // 多选 ClipData clipdata = resultIntent.getClipData(); if (clipdata.getItemCount() > 0) { uri = clipdata.getItemAt(0).getUri(); } } if (uri == null) { showToast(R.string.avatar_pic_has_not_select); return; } String path = MediaHelper.getPath(this, uri); if (TextUtils.isEmpty(path)) { showToast(R.string.avatar_pic_not_fount); return; } // 启动裁剪 Intent intent = new Intent(this, AvatarClipActivity.class); intent.putExtra(AvatarClipActivity.KEY_BITMAP_PATH, path); startActivity(intent); break; // 年龄 case REQUEST_CODE_AGE: { Serializable data = resultIntent.getSerializableExtra(EditorDialogActivity.KEY_RESULT_DATA); String dateStr = new SimpleDateFormat("yyyy-MM-dd").format((Date) data); mUserInfo.setBirthday(dateStr); updateCurrentLoginUserInfo(); } break; // TODO 地区选择 case REQUEST_CODE_PLACE: { int placeid = resultIntent.getIntExtra(EditorDialogActivity.KEY_RESULT_DATA, 0); if (placeid != 0) { mUserInfo.setCity(String.valueOf(placeid)); updateCurrentLoginUserInfo(); } } break; case REQUEST_CODE_DESCRIPTION: { String description = (String) resultIntent.getSerializableExtra(EditorDialogActivity.KEY_RESULT_DATA); mUserInfo.setDescription(description); updateCurrentLoginUserInfo(); } break; case REQUEST_CODE_SEX: { int sex = resultIntent.getIntExtra(EditorDialogActivity.KEY_RESULT_DATA, Constant.SEX_UNKONW); mUserInfo.setSex(sex); updateCurrentLoginUserInfo(); } break; default: break; } }
/** * Required for reacting to selected bitmaps from galleries. Loads and prepares bitmaps * asynchronously, showing progress on the fly and an indeterminate progress bar. * * @param requestCode The request code of the activity result started for intent. * @param resultCode The result code. Does nothing if not ok. * @param data The returned data. */ public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK || requestCode != WorkshopView.PICK_IMAGES_FOR_BUNDLE || data == null) { return; } ClipData clipData = data.getClipData(); Uri[] selectedImageUris; if (clipData == null) { selectedImageUris = new Uri[] {data.getData()}; } else { selectedImageUris = new Uri[clipData.getItemCount()]; for (int i = 0; i < clipData.getItemCount(); i++) { ClipData.Item curr = clipData.getItemAt(i); selectedImageUris[i] = curr.getUri(); } } new AsyncTask<Uri, SelectedBitmap, Void>() { @Override public void onPreExecute() { ensureTempDirectory(); mBitmapsSelectCount++; if (mBitmapsSelectCount > 0) { mBitmapsSelectProgress.setVisibility(View.VISIBLE); } } @Override protected Void doInBackground(Uri... params) { String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE, MediaStore.Images.Media.DISPLAY_NAME }; for (Uri selectedImages : params) { if (selectedImages == null) { continue; } Cursor cursor = null; try { cursor = mActivity.getContentResolver().query(selectedImages, columns, null, null, null); if (cursor == null || cursor.isAfterLast()) { continue; // empty cursor } cursor.moveToFirst(); int pathIndex = cursor.getColumnIndexOrThrow(columns[0]); int sizeIndex = cursor.getColumnIndexOrThrow(columns[1]); int nameIndex = cursor.getColumnIndex(columns[2]); while (!cursor.isAfterLast()) { String picturePath = cursor.getString(pathIndex); int sizeKB = cursor.getInt(sizeIndex) / (1024); if (picturePath == null) { InputStream input = null; try { input = mActivity.getContentResolver().openInputStream(selectedImages); } catch (FileNotFoundException e1) { Log.e( "HomeStuff", "File not found when trying to decode bitmap from stream: " + e1); } String bitmapName = null; if (nameIndex != -1) { bitmapName = cursor.getString(nameIndex); } if (TextUtils.isEmpty(bitmapName)) { bitmapName = String.valueOf(System.currentTimeMillis()); } File bitmapFileInTemp = new File(mTempDirectory, bitmapName); Bitmap bitmap = ImageUtil.loadBitmap( input, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT, BitmapUtil.MODE_FIT_NO_GROW); if (ImageUtil.saveToFile(bitmap, bitmapFileInTemp, null, COMPRESSION)) { publishProgress(new SelectedBitmap(bitmap, bitmapFileInTemp, sizeKB, mBuffer)); } } else { File path = new File(picturePath); String bitmapName = path.getName(); if (TextUtils.isEmpty(bitmapName) && nameIndex != -1) { bitmapName = cursor.getString(nameIndex); } File targetPath = new File(mTempDirectory, bitmapName); Bitmap bitmap = ImageUtil.loadBitmap( path, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT, BitmapUtil.MODE_FIT_NO_GROW); if (ImageUtil.saveToFile(bitmap, targetPath, null, COMPRESSION)) { publishProgress(new SelectedBitmap(bitmap, targetPath, sizeKB, mBuffer)); } } cursor.moveToNext(); } } catch (Exception e) { Log.e("HomeStuff", "Error retrieving images from cursor " + cursor + ": " + e); } finally { if (cursor != null) { cursor.close(); } } } return null; } @Override public void onProgressUpdate(SelectedBitmap... bitmap) { if (!isImageSelected(bitmap[0].mPathInTemp.getAbsolutePath())) { synchronized (mSelectedBitmaps) { mSelectedBitmaps.add(bitmap[0]); } } mSaveResult = ImageXmlWriter.RESULT_NONE; fillSelectedBitmapsData(); updateStatus(); } @Override public void onPostExecute(Void nothing) { mSaveResult = ImageXmlWriter.RESULT_NONE; Log.d( "HomeStuff", "Finished loading bitmaps (Processes still loading: " + (mBitmapsSelectCount - 1) + ")."); mBitmapsSelectCount--; if (mBitmapsSelectCount <= 0) { mBitmapsSelectProgress.setVisibility(View.INVISIBLE); } applyOrigin(); fillSelectedBitmapsData(); updateStatus(); } }.execute(selectedImageUris); }
private final void checkDataOwnerLocked(ClipData data, int uid) { final int N = data.getItemCount(); for (int i = 0; i < N; i++) { checkItemOwnerLocked(data.getItemAt(i), uid); } }
public static boolean hasText(Context context) { ClipboardManager clipboard = getManager(context); ClipData clip = clipboard.getPrimaryClip(); return clip != null && clip.getItemCount() > 0; }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case REQUEST_CODE_TAKEN_PHOTO_CAMERA: { if (data != null) { final Bitmap bitmap = (Bitmap) data.getExtras().get("data"); onImageTaken(bitmap); break; } } case REQUEST_CODE_TAKEN_PHOTO_GALLERY: { if (data != null) { if (data.getParcelableArrayListExtra("uris") != null) { List<Uri> uriList = data.getParcelableArrayListExtra("uris"); for (int i = 0; i < uriList.size(); i++) { new GetBitmapFromUriTask( this, uriList.get(i), new GetBitmapFromUriTask.IOnImageTakenListener() { @Override public void onImageTaken(final Bitmap pBitmap) { MainActivity.this.onImageTaken(pBitmap); } }) .execute(); } } else if (data.getData() == null) { ClipData clipData = data.getClipData(); for (int i = 0; i < clipData.getItemCount(); i++) { ClipData.Item item = clipData.getItemAt(i); new GetBitmapFromUriTask( this, item.getUri(), new GetBitmapFromUriTask.IOnImageTakenListener() { @Override public void onImageTaken(final Bitmap pBitmap) { MainActivity.this.onImageTaken(pBitmap); } }) .execute(); } } else { new GetBitmapFromUriTask( this, data.getData(), new GetBitmapFromUriTask.IOnImageTakenListener() { @Override public void onImageTaken(final Bitmap pBitmap) { MainActivity.this.onImageTaken(pBitmap); } }) .execute(); } break; } } } } }