List of usage examples for android.content Intent getData
public @Nullable Uri getData()
From source file:edu.mit.viral.shen.DroidFish.java
private final Pair<String, String> getPgnOrFenIntent() { String pgnOrFen = null;//from w w w . j ava 2 s.c o m String filename = null; try { Intent intent = getIntent(); Uri data = intent.getData(); if (data == null) { if ((Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction())) && ("application/x-chess-pgn".equals(intent.getType()) || "application/x-chess-fen".equals(intent.getType()))) pgnOrFen = intent.getStringExtra(Intent.EXTRA_TEXT); } else { String scheme = intent.getScheme(); if ("file".equals(scheme)) { filename = data.getEncodedPath(); if (filename != null) filename = Uri.decode(filename); } if ((filename == null) && ("content".equals(scheme) || "file".equals(scheme))) { ContentResolver resolver = getContentResolver(); InputStream in = resolver.openInputStream(intent.getData()); StringBuilder sb = new StringBuilder(); while (true) { byte[] buffer = new byte[16384]; int len = in.read(buffer); if (len <= 0) break; sb.append(new String(buffer, 0, len)); } pgnOrFen = sb.toString(); } } } catch (IOException e) { Toast.makeText(getApplicationContext(), R.string.failed_to_read_pgn_data, Toast.LENGTH_SHORT).show(); } return new Pair<String, String>(pgnOrFen, filename); }
From source file:cl.gisred.android.InspActivity.java
@TargetApi(Build.VERSION_CODES.KITKAT) @Override//from w ww . ja v a 2 s. c o m public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { PhotoUtils photoUtils = new PhotoUtils(getApplicationContext()); //Cambio de orientacion imgTemp = null if (imgTemp == null) { Toast.makeText(getApplicationContext(), "Ocupe la misma orientacin en que est usando GISRED", Toast.LENGTH_LONG).show(); return; } //Parche temporal cambios de ajuste if (Build.VERSION.SDK_INT < 23) imgTemp.setAdjustViewBounds(true); imgTemp.setCropToPadding(true); if (requestCode == ACTIVITY_SELECT_IMAGE) { mImageUri = data.getData(); Log.w("onActivityResult", "URI: " + mImageUri.getPath()); imgTemp.setImageBitmap(photoUtils.getImage(mImageUri, 250)); try { photoUtils.copyFromGallery(mImageUri, sImgUri); } catch (Exception e) { e.printStackTrace(); } } else if (requestCode == ACTIVITY_SELECT_FROM_CAMERA) { Log.w("onActivityResult", "URI: " + mImageUri.getPath()); photoUtils.copyToGallery(mImageUri); Bitmap oBitmap = photoUtils.getImage(mImageUri, 250); Log.w("onActivityResult", String.format("W: %s H: %s", oBitmap.getWidth(), oBitmap.getHeight())); imgTemp.setImageBitmap(oBitmap); } } }
From source file:com.example.zf_android.trade.ApplyDetailActivity.java
@Override protected void onActivityResult(final int requestCode, int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) return;// ww w .j a va 2 s.c o m switch (requestCode) { case REQUEST_CHOOSE_MERCHANT: { mAgentId = mMerchantId = data.getIntExtra(AGENT_ID, 0); mAgentName = data.getStringExtra(AGENT_NAME); setItemValue(mMerchantKeys[0], mAgentName); getAgentInfo(); break; } case REQUEST_CHOOSE_BANK: { mBankName = data.getStringExtra("bank_name"); mBankNo = data.getStringExtra("bank_no"); setItemValue(customTag, mBankName); setItemValue(mBankKeys[0], mBankName); //FIXME no // setItemValue(mBankKeys[1], mBankNo); break; } case REQUEST_CHOOSE_CITY: { mMerchantProvince = (Province) data.getSerializableExtra(SELECTED_PROVINCE); mMerchantCity = (City) data.getSerializableExtra(SELECTED_CITY); mCityId = mMerchantCity.getId(); setItemValue(mMerchantKeys[8], mMerchantCity.getName()); break; } case REQUEST_CHOOSE_CHANNEL: { mChannelId = data.getIntExtra("channelId", 0); mBillingId = data.getIntExtra("billId", 0); String channelName = data.getStringExtra("channelName"); String billName = data.getStringExtra("billName"); setItemValue(getString(R.string.apply_detail_channel), channelName + " " + billName); break; } case REQUEST_UPLOAD_IMAGE: case REQUEST_TAKE_PHOTO: { final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { // CommonUtil.toastShort(ApplyDetailActivity.this, (String) msg.obj); if (null != uploadingTextView) { final String url = (String) msg.obj; LinearLayout item = (LinearLayout) uploadingTextView.getParent().getParent(); updateCustomerDetails(item.getTag(), url); uploadingTextView.setVisibility(View.GONE); ImageView iv_view = (ImageView) item.findViewById(R.id.apply_detail_view); iv_view.setVisibility(View.VISIBLE); iv_view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(ApplyDetailActivity.this, ImageViewer.class); i.putExtra("url", url); i.putExtra("justviewer", true); startActivity(i); } }); } } else { CommonUtil.toastShort(ApplyDetailActivity.this, getString(R.string.toast_upload_failed)); if (null != uploadingTextView) { uploadingTextView.setText(getString(R.string.apply_upload_again)); uploadingTextView.setClickable(true); } } } }; if (null != uploadingTextView) { uploadingTextView.setText(getString(R.string.apply_uploading)); uploadingTextView.setClickable(false); } new Thread() { @Override public void run() { String realPath = ""; if (requestCode == REQUEST_TAKE_PHOTO) { realPath = photoPath; } else { Uri uri = data.getData(); if (uri != null) { realPath = getRealPathFromURI(uri); } } if (TextUtils.isEmpty(realPath)) { handler.sendEmptyMessage(0); return; } CommonUtil.uploadFile(realPath, "img", new CommonUtil.OnUploadListener() { @Override public void onSuccess(String result) { try { JSONObject jo = new JSONObject(result); String url = jo.getString("result"); Message msg = new Message(); msg.what = 1; msg.obj = url; handler.sendMessage(msg); } catch (JSONException e) { handler.sendEmptyMessage(0); } } @Override public void onFailed(String message) { handler.sendEmptyMessage(0); } }); } }.start(); break; } } }
From source file:com.ieeton.user.activity.ChatActivity.java
/** * onActivityResult//from w w w . ja v a2 s . c o m */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_CODE_EXIT_GROUP) { setResult(RESULT_OK); finish(); return; } if (requestCode == REQUEST_CODE_CONTEXT_MENU) { switch (resultCode) { case RESULT_CODE_COPY: // ?? EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra("position", -1))); // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this, // ((TextMessageBody) copyMsg.getBody()).getMessage())); clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage()); break; case RESULT_CODE_DELETE: // ? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); conversation.removeMessage(deleteMsg.getMsgId()); adapter.refresh(); listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1); break; default: break; } } if (resultCode == RESULT_OK) { // ? if (requestCode == REQUEST_CODE_EMPTY_HISTORY) { // ? EMChatManager.getInstance().clearConversation(toChatUsername); adapter.refresh(); } else if (requestCode == REQUEST_CODE_CAMERA) { // ?? if (cameraFile != null && cameraFile.exists()) sendPicture(cameraFile.getAbsolutePath()); } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // ?? int duration = data.getIntExtra("dur", 0); String videoPath = data.getStringExtra("path"); File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis()); Bitmap bitmap = null; FileOutputStream fos = null; try { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3); if (bitmap == null) { EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon"); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon); } fos = new FileOutputStream(file); bitmap.compress(CompressFormat.JPEG, 100, fos); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } fos = null; } if (bitmap != null) { bitmap.recycle(); bitmap = null; } } sendVideo(videoPath, file.getAbsolutePath(), duration / 1000); } else if (requestCode == REQUEST_CODE_LOCAL) { // ?? if (data != null) { Uri selectedImage = data.getData(); if (selectedImage != null) { sendPicByUri(selectedImage); } } } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // ?? if (data != null) { Uri uri = data.getData(); if (uri != null) { sendFile(uri); } } } else if (requestCode == REQUEST_CODE_MAP) { // double latitude = data.getDoubleExtra("latitude", 0); double longitude = data.getDoubleExtra("longitude", 0); String locationAddress = data.getStringExtra("address"); if (locationAddress != null && !locationAddress.equals("")) { more(more); sendLocationMsg(latitude, longitude, "", locationAddress); } else { Toast.makeText(this, "????", 0).show(); } // ??? } else if (requestCode == REQUEST_CODE_TEXT) { resendMessage(); } else if (requestCode == REQUEST_CODE_VOICE) { resendMessage(); } else if (requestCode == REQUEST_CODE_PICTURE) { resendMessage(); } else if (requestCode == REQUEST_CODE_LOCATION) { resendMessage(); } else if (requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) { resendMessage(); } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) { // if (!TextUtils.isEmpty(clipboard.getText())) { String pasteText = clipboard.getText().toString(); if (pasteText.startsWith(COPY_IMAGE)) { // ??path sendPicture(pasteText.replace(COPY_IMAGE, "")); } } } else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // ??? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); addUserToBlacklist(deleteMsg.getFrom()); } else if (conversation.getMsgCount() > 0) { adapter.refresh(); setResult(RESULT_OK); } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) { adapter.refresh(); } } }
From source file:key.secretkey.SettingsActivity.java
/** * Opens a key generator to generate a public/private key pair *//*from w w w . j ava 2 s . c om*/ // public void makeSshKey(boolean fromPreferences) { // Intent intent = new Intent(getApplicationContext(), SshKeyGen.class); // startActivity(intent); // if (!fromPreferences) { // setResult(RESULT_OK); // finish(); // } // } // private void copySshKey(Uri uri) throws IOException { // InputStream sshKey = this.getContentResolver().openInputStream(uri); // byte[] privateKey = IOUtils.toByteArray(sshKey); // FileUtils.writeByteArrayToFile(new File(getFilesDir() + "/.ssh_key"), privateKey); // sshKey.close(); // } // Returns whether the autofill service is enabled // private boolean isServiceEnabled() { // AccessibilityManager am = (AccessibilityManager) this // .getSystemService(Context.ACCESSIBILITY_SERVICE); // List<AccessibilityServiceInfo> runningServices = am // .getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC); // for (AccessibilityServiceInfo service : runningServices) { // if ("com.zeapo.pwdstore/.autofill.AutofillService".equals(service.getId())) { // return true; // } // } // return false; // } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { // case IMPORT_SSH_KEY: { // try { // final Uri uri = data.getData(); // // if (uri == null) { // throw new IOException("Unable to open file"); // } // copySshKey(uri); // Toast.makeText(this, this.getResources().getString(R.string.ssh_key_success_dialog_title), Toast.LENGTH_LONG).show(); // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // SharedPreferences.Editor editor = prefs.edit(); // editor.putBoolean("use_generated_key", false); // editor.apply(); // // //delete the public key from generation // File file = new File(getFilesDir() + "/.ssh_key.pub"); // file.delete(); // // setResult(RESULT_OK); // finish(); // } catch (IOException e) { // new AlertDialog.Builder(this). // setTitle(this.getResources().getString(R.string.ssh_key_error_dialog_title)). // setMessage(this.getResources().getString(R.string.ssh_key_error_dialog_text) + e.getMessage()). // setPositiveButton(this.getResources().getString(R.string.dialog_ok), new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialogInterface, int i) { // // pass // } // }).show(); // } // } // break; // case EDIT_GIT_INFO: { // // } // break; // case SELECT_GIT_DIRECTORY: { // final Uri uri = data.getData(); // // if (uri.getPath().equals(Environment.getExternalStorageDirectory().getPath())) { // // the user wants to use the root of the sdcard as a store... // new AlertDialog.Builder(this). // setTitle("SD-Card root selected"). // setMessage("You have selected the root of your sdcard for the store. " + // "This is extremely dangerous and you will lose your data " + // "as its content will, eventually, be deleted"). // setPositiveButton("Remove everything", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) // .edit() // .putString("git_external_repo", uri.getPath()) // .apply(); // } // }). // setNegativeButton(R.string.dialog_cancel, null).show(); // } else { // PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) // .edit() // .putString("git_external_repo", uri.getPath()) // .apply(); // } // } // break; case EXPORT_PASSWORDS: { final Uri uri = data.getData(); final File repositoryDirectory = PasswordStorage.getRepositoryDirectory(getApplicationContext()); SimpleDateFormat fmtOut = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US); Date date = new Date(); String password_now = "/password_store_" + fmtOut.format(date); final File targetDirectory = new File(uri.getPath() + password_now); if (repositoryDirectory != null) { try { FileUtils.copyDirectory(repositoryDirectory, targetDirectory, true); } catch (IOException e) { Log.d("PWD_EXPORT", "Exception happened : " + e.getMessage()); } } } break; default: break; } } }
From source file:com.guardtrax.ui.screens.HomeScreen.java
protected void onActivityResult(final int requestCode, int resultCode, final Intent data) { if (resultCode == RESULT_CANCELED) return;//from w w w . java2s .co m //After running Media Gallery Program if (requestCode == ACTIVITY_SELECT_IMAGE) { Uri_image = data.getData(); Intent i = new Intent(HomeScreen.this, SingleImageView.class); startActivity(i); return; } if (requestCode == ACTIVITY_SELECT_VIDEO) { Uri_image = data.getData(); Intent intent = new Intent(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri_image, "video/mpeg"); startActivity(intent); return; } //after running audio program if (requestCode == REQUEST_CODE_RECORD) { //move file into GT/s directory Uri savedUri = data.getData(); Cursor cursor = getContentResolver().query(savedUri, null, null, null, null); if (cursor.moveToFirst()) { int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data" Uri filePathUri = Uri.parse(cursor.getString(column_index)); String file_path = filePathUri.getPath(); //rename the file String path = GTConstants.sendfileFolder + Utility.createFileName() + ".3ga"; //put the file name into the global file_name = path; File file_to = new File(path); File file_from = new File(file_path); file_from.renameTo(file_to); //Toast.makeText(HomeScreen.this, file_name, Toast.LENGTH_LONG).show(); } } //after running camera, audio or video program if (requestCode == REQUEST_CODE_RECORD || requestCode == CAMERA_PIC_REQUEST || requestCode == ACTION_TAKE_VIDEO) { //this section was pulled from the "Cancel" option of the the tagging code - it replaces tagging (i.e. as if cancel is always being selected try { //copy file to /GT/r directory so that local user can view the image File file = new File(file_name); copyFile(GTConstants.sendfileFolder, file.getName(), GTConstants.receivefileFolder); //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone //sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory()))); sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); //new Upload_FTP().execute(file_name); Utility.setUploadAvailable(); } catch (Exception e) { Toast.makeText(HomeScreen.this, "File copy Error: " + e, Toast.LENGTH_LONG).show(); } //create filename info for dar String darFile[] = null; String newFile; try { darFile = file_name.split("_"); newFile = GTConstants.LICENSE_ID.substring(7) + "_" + darFile[1] + "_" + darFile[2]; //Toast.makeText(HomeScreen.this, "File: " + newFile, Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(HomeScreen.this, "File Naming Error: " + e, Toast.LENGTH_LONG).show(); newFile = "unknown"; } //email option if (requestCode == REQUEST_CODE_RECORD) { //add event to dar and srp if (GTConstants.sendData) { Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.darfileName, "Voice;" + newFile + ".3ga" + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); if (GTConstants.srpfileName.length() > 1) Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.srpfileName, "Voice;" + newFile + ".3ga" + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); } send_media_via_email("audio"); } if (requestCode == CAMERA_PIC_REQUEST) { //add event to dar and srp if (GTConstants.sendData) { Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.darfileName, "Photo;" + newFile + ".jpg" + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); if (GTConstants.srpfileName.length() > 1) Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.srpfileName, "Photo;" + newFile + ".jpg" + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); } send_media_via_email("photo"); } if (requestCode == ACTION_TAKE_VIDEO) { //add event to dar if (GTConstants.sendData) { Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.darfileName, "Video;" + newFile + ".mpeg" + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); if (GTConstants.srpfileName.length() > 1) Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.srpfileName, "Video;" + newFile + ".mpeg" + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); } send_media_via_email("video"); } //end cancel section /* Allowing fore tagging of media files removed 7/1/14 - B. Hall //after taking audio, camera or video this routine fires. file_name is a common variable file name that is assigned when an audio, camera or video is taken AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this); dialog.setTitle("Tag"); dialog.setMessage("Add a tag?"); final EditText input = new EditText(this); dialog.setView(input); dialog.setPositiveButton("OK",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int which) { String tagText = input.getText().toString().trim(); //rename the file File currentFile = new File(file_name); String path = GTConstants.sendfileFolder; String oldFile = currentFile.getName(); String newFile = oldFile.substring(0, oldFile.lastIndexOf('.')) + "_" + tagText + "_"; if (requestCode == CAMERA_PIC_REQUEST) { //rename the file to include tag newFile = newFile + ".jpg"; file_name = path + newFile; File from = new File(path,oldFile); File to = new File(path,newFile); from.renameTo(to); //now upload the file to the ftp server //new Upload_FTP().execute(file_name); Utility.setUploadAvailable(); //email option send_media_via_email("photo"); //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory()))); //Toast.makeText(HomeScreen.this, "Picture saved", Toast.LENGTH_LONG).show(); } if (requestCode == ACTION_TAKE_VIDEO) { newFile = newFile + ".mpeg"; file_name = path + newFile; File from = new File(path,oldFile); File to = new File(path,newFile); from.renameTo(to); //new Upload_FTP().execute(file_name); Utility.setUploadAvailable(); //email option send_media_via_email("video"); //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); //Toast.makeText(HomeScreen.this, "Video saved", Toast.LENGTH_LONG).show(); } if (requestCode == REQUEST_CODE_RECORD) { newFile = newFile + ".3ga"; file_name = path + newFile; File from = new File(path,oldFile); File to = new File(path,newFile); from.renameTo(to); //new Upload_FTP().execute(file_name); Utility.setUploadAvailable(); //email option send_media_via_email("audio"); //Toast.makeText(HomeScreen.this, "Audio saved", Toast.LENGTH_LONG).show(); } //copy file to /GT/r directory so that local user can view the image copyFile(GTConstants.sendfileFolder, newFile, GTConstants.receivefileFolder); //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory()))); } }); //if no tag is added then leave the filename alone, it was set during initial save (although issue still exists with audio filename!!!). dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //copy file to /GT/r directory so that local user can view the image File file = new File(file_name); copyFile(GTConstants.sendfileFolder, file.getName(), GTConstants.receivefileFolder); //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory()))); //new Upload_FTP().execute(file_name); Utility.setUploadAvailable(); //email option if (requestCode == REQUEST_CODE_RECORD)send_media_via_email("audio"); if (requestCode == CAMERA_PIC_REQUEST) send_media_via_email("photo"); if (requestCode == ACTION_TAKE_VIDEO) send_media_via_email("video"); } }); dialog.show(); */ } }
From source file:com.if3games.chessonline.DroidFish.java
/** * Return PGN/FEN data or filename from the Intent. Both can not be non-null. * @return Pair of PGN/FEN data and filename. */// w w w . ja v a 2 s. c o m private final Pair<String, String> getPgnOrFenIntent() { String pgnOrFen = null; String filename = null; try { Intent intent = getIntent(); Uri data = intent.getData(); if (data == null) { Bundle b = intent.getExtras(); if (b != null) { Object strm = b.get(Intent.EXTRA_STREAM); if (strm instanceof Uri) { data = (Uri) strm; if ("file".equals(data.getScheme())) { filename = data.getEncodedPath(); if (filename != null) filename = Uri.decode(filename); } } } } if (data == null) { if ((Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction())) && ("application/x-chess-pgn".equals(intent.getType()) || "application/x-chess-fen".equals(intent.getType()))) pgnOrFen = intent.getStringExtra(Intent.EXTRA_TEXT); } else { String scheme = intent.getScheme(); if ("file".equals(scheme)) { filename = data.getEncodedPath(); if (filename != null) filename = Uri.decode(filename); } if ((filename == null) && ("content".equals(scheme) || "file".equals(scheme))) { ContentResolver resolver = getContentResolver(); InputStream in = resolver.openInputStream(intent.getData()); StringBuilder sb = new StringBuilder(); while (true) { byte[] buffer = new byte[16384]; int len = in.read(buffer); if (len <= 0) break; sb.append(new String(buffer, 0, len)); } pgnOrFen = sb.toString(); } } } catch (IOException e) { Toast.makeText(getApplicationContext(), R.string.failed_to_read_pgn_data, Toast.LENGTH_SHORT).show(); } return new Pair<String, String>(pgnOrFen, filename); }
From source file:com.aidigame.hisun.imengstar.huanxin.ChatActivity.java
/** * onActivityResult// w ww. j av a2 s. co m */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_CODE_EXIT_GROUP) { setResult(RESULT_OK); finish(); return; } if (requestCode == REQUEST_CODE_CONTEXT_MENU) { switch (resultCode) { case RESULT_CODE_COPY: // ?? EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra("position", -1))); // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this, // ((TextMessageBody) copyMsg.getBody()).getMessage())); clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage()); break; case RESULT_CODE_DELETE: // ? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); conversation.removeMessage(deleteMsg.getMsgId()); adapter.refresh(); listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1); break; case RESULT_CODE_FORWARD: // ?? EMMessage forwardMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", 0)); Intent intent = new Intent(this, ForwardMessageActivity.class); intent.putExtra("forward_msg_id", forwardMsg.getMsgId()); startActivity(intent); break; default: break; } } if (resultCode == RESULT_OK) { // ? if (requestCode == REQUEST_CODE_EMPTY_HISTORY) { // ? EMChatManager.getInstance().clearConversation(toChatUsername); adapter.refresh(); } else if (requestCode == REQUEST_CODE_CAMERA) { // ?? if (cameraFile != null && cameraFile.exists()) sendPicture(cameraFile.getAbsolutePath()); } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // ?? int duration = data.getIntExtra("dur", 0); String videoPath = data.getStringExtra("path"); File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis()); Bitmap bitmap = null; FileOutputStream fos = null; try { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3); if (bitmap == null) { EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon"); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon); } fos = new FileOutputStream(file); bitmap.compress(CompressFormat.JPEG, 100, fos); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } fos = null; } if (bitmap != null) { bitmap.recycle(); bitmap = null; } } sendVideo(videoPath, file.getAbsolutePath(), duration / 1000); } else if (requestCode == REQUEST_CODE_LOCAL) { // ?? if (data != null) { Uri selectedImage = data.getData(); if (selectedImage != null) { sendPicByUri(selectedImage); } } } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // ?? if (data != null) { Uri uri = data.getData(); if (uri != null) { sendFile(uri); } } } else if (requestCode == REQUEST_CODE_MAP) { // double latitude = data.getDoubleExtra("latitude", 0); double longitude = data.getDoubleExtra("longitude", 0); String locationAddress = data.getStringExtra("address"); if (locationAddress != null && !locationAddress.equals("")) { more(more); sendLocationMsg(latitude, longitude, "", locationAddress); } else { Toast.makeText(this, "????", 0).show(); } // ??? } else if (requestCode == REQUEST_CODE_TEXT || requestCode == REQUEST_CODE_VOICE || requestCode == REQUEST_CODE_PICTURE || requestCode == REQUEST_CODE_LOCATION || requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) { resendMessage(); } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) { // if (!TextUtils.isEmpty(clipboard.getText())) { String pasteText = clipboard.getText().toString(); if (pasteText.startsWith(COPY_IMAGE)) { // ??path sendPicture(pasteText.replace(COPY_IMAGE, "")); } } } else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // ??? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); addUserToBlacklist(deleteMsg.getFrom()); } else if (conversation.getMsgCount() > 0) { adapter.refresh(); setResult(RESULT_OK); } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) { adapter.refresh(); } } }
From source file:com.tealeaf.TeaLeaf.java
protected void onActivityResult(int request, int result, Intent data) { super.onActivityResult(request, result, data); PluginManager.callAll("onActivityResult", request, result, data); logger.log("GOT ACTIVITY RESULT WITH", request, result); switch (request) { case PhotoPicker.CAPTURE_IMAGE: if (result == RESULT_OK) { EventQueue.pushEvent(new PhotoBeginLoadedEvent()); Bitmap bmp = null;/*from w ww . ja va 2s .c o m*/ if (data != null) { Bundle extras = data.getExtras(); //try and get bitmap off of intent if (extras != null) { bmp = (Bitmap) extras.get("data"); } } //try the large file on disk final File f = PhotoPicker.getCaptureImageTmpFile(); if (f != null && f.exists()) { new Thread(new Runnable() { public void run() { Bitmap bmp = null; String filePath = f.getAbsolutePath(); try { bmp = BitmapFactory.decodeFile(filePath); } catch (OutOfMemoryError e) { System.gc(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; bmp = BitmapFactory.decodeFile(filePath, options); } if (bmp != null) { try { File f = new File(filePath); ExifInterface exif = new ExifInterface(f.getAbsolutePath()); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); if (orientation != ExifInterface.ORIENTATION_NORMAL) { int rotateBy = 0; switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotateBy = ROTATE_90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotateBy = ROTATE_180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotateBy = ROTATE_270; break; } Bitmap rotatedBmp = rotateBitmap(bmp, rotateBy); if (rotatedBmp != bmp) { bmp.recycle(); } bmp = rotatedBmp; } } catch (Exception e) { logger.log(e); } f.delete(); if (bmp != null) { glView.getTextureLoader() .saveCameraPhoto(glView.getTextureLoader().getCurrentPhotoId(), bmp); glView.getTextureLoader().finishCameraPicture(); } else { glView.getTextureLoader().failedCameraPicture(); } } } }).start(); } else { glView.getTextureLoader().saveCameraPhoto(glView.getTextureLoader().getCurrentPhotoId(), bmp); glView.getTextureLoader().finishCameraPicture(); } } else { glView.getTextureLoader().failedCameraPicture(); } break; case PhotoPicker.PICK_IMAGE: if (result == RESULT_OK) { final Uri selectedImage = data.getData(); EventQueue.pushEvent(new PhotoBeginLoadedEvent()); String[] filePathColumn = { MediaColumns.DATA, MediaStore.Images.ImageColumns.ORIENTATION }; String _filepath = null; try { Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); _filepath = cursor.getString(columnIndex); columnIndex = cursor.getColumnIndex(filePathColumn[1]); int orientation = cursor.getInt(columnIndex); cursor.close(); } catch (Exception e) { } final String filePath = _filepath; new Thread(new Runnable() { public void run() { if (filePath == null) { BitmapFactory.Options options = new BitmapFactory.Options(); InputStream inputStream; Bitmap bmp = null; try { inputStream = getContentResolver().openInputStream(selectedImage); bmp = BitmapFactory.decodeStream(inputStream, null, options); inputStream.close(); } catch (Exception e) { logger.log(e); } if (bmp != null) { glView.getTextureLoader() .saveGalleryPicture(glView.getTextureLoader().getCurrentPhotoId(), bmp); glView.getTextureLoader().finishGalleryPicture(); } else { glView.getTextureLoader().failedGalleryPicture(); } } else { Bitmap bmp = null; try { bmp = BitmapFactory.decodeFile(filePath); } catch (OutOfMemoryError e) { System.gc(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; bmp = BitmapFactory.decodeFile(filePath, options); } if (bmp != null) { try { File f = new File(filePath); ExifInterface exif = new ExifInterface(f.getAbsolutePath()); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); if (orientation != ExifInterface.ORIENTATION_NORMAL) { int rotateBy = 0; switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotateBy = ROTATE_90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotateBy = ROTATE_180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotateBy = ROTATE_270; break; } Bitmap rotatedBmp = rotateBitmap(bmp, rotateBy); if (rotatedBmp != bmp) { bmp.recycle(); } bmp = rotatedBmp; } } catch (Exception e) { logger.log(e); } if (bmp != null) { glView.getTextureLoader() .saveGalleryPicture(glView.getTextureLoader().getCurrentPhotoId(), bmp); glView.getTextureLoader().finishGalleryPicture(); } else { glView.getTextureLoader().failedGalleryPicture(); } } } } }).start(); } else { glView.getTextureLoader().failedGalleryPicture(); } break; } }