List of usage examples for android.content ContentResolver openInputStream
public final @Nullable InputStream openInputStream(@NonNull Uri uri) throws FileNotFoundException
From source file:com.mobicage.rogerthat.util.ui.SendMessageView.java
private void copyVideoFile(final Uri selectedVideo) { final ContentResolver cr = mActivity.getContentResolver(); final ProgressDialog progressDialog = showProcessing(); new SafeAsyncTask<Object, Object, Boolean>() { @Override/* ww w . jav a 2 s . c o m*/ protected Boolean safeDoInBackground(Object... params) { L.d("Processing video: " + selectedVideo.toString()); try { if (mTmpUploadFile.getAbsolutePath().equals(selectedVideo.getPath())) { return true; } else { InputStream is = cr.openInputStream(selectedVideo); if (is != null) { try { OutputStream out = new FileOutputStream(mTmpUploadFile); try { IOUtils.copy(is, out, 1024); } finally { out.close(); } } finally { is.close(); } return true; } } } catch (FileNotFoundException e) { L.d(e); } catch (Exception e) { L.bug("Unknown exception occured while processing video: " + selectedVideo.toString(), e); } return false; }; @Override protected void safeOnPostExecute(Boolean result) { progressDialog.dismiss(); if (result) { setVideoSelected(); } else { UIUtils.showLongToast(mActivity, mActivity.getString(R.string.error_please_try_again)); } } @Override protected void safeOnCancelled(Boolean result) { } @Override protected void safeOnProgressUpdate(Object... values) { } @Override protected void safeOnPreExecute() { }; }.execute(); }
From source file:com.fvd.nimbus.PaintActivity.java
/** Called when the activity is first created. */ @Override//from w w w .ja v a2 s .co m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up ); overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); try { requestWindowFeature(Window.FEATURE_NO_TITLE); } catch (Exception e) { e.printStackTrace(); } ctx = this; prefs = PreferenceManager.getDefaultSharedPreferences(this); dWidth = prefs.getInt("dWidth", 2); fWidth = prefs.getInt("fWidth", 1); dColor = prefs.getInt(pColor, Color.RED); saveFormat = Integer.parseInt(prefs.getString("saveFormat", "1")); serverHelper.getInstance().setCallback(this, this); serverHelper.getInstance().setMode(saveFormat); setContentView(R.layout.screen_edit); drawer = (DrawerLayout) findViewById(R.id.root); findViewById(R.id.bDraw1).setOnClickListener(this); findViewById(R.id.bDraw2).setOnClickListener(this); findViewById(R.id.bDraw3).setOnClickListener(this); findViewById(R.id.bDraw4).setOnClickListener(this); findViewById(R.id.bDraw5).setOnClickListener(this); findViewById(R.id.bDraw6).setOnClickListener(this); findViewById(R.id.bDraw8).setOnClickListener(this); findViewById(R.id.bColor1).setOnClickListener(this); findViewById(R.id.bColor2).setOnClickListener(this); findViewById(R.id.bColor3).setOnClickListener(this); findViewById(R.id.bColor4).setOnClickListener(this); findViewById(R.id.bColor5).setOnClickListener(this); paletteButton = (CircleButton) findViewById(R.id.bToolColor); paletteButton.setOnClickListener(this); paletteButton_land = (CircleButton) findViewById(R.id.bToolColor_land); //paletteButton_land.setOnClickListener(this); ((SeekBar) findViewById(R.id.seekBarLine)).setProgress(dWidth * 10); ((SeekBar) findViewById(R.id.seekBarType)).setProgress(fWidth * 10); ((TextView) findViewById(R.id.tvTextType)).setText(String.format("%d", 40 + fWidth * 20)); findViewById(R.id.bUndo).setOnClickListener(this); findViewById(R.id.btnBack).setOnClickListener(this); findViewById(R.id.bClearAll).setOnClickListener(this); findViewById(R.id.bTurnLeft).setOnClickListener(this); findViewById(R.id.bTurnRight).setOnClickListener(this); findViewById(R.id.bDone).setOnClickListener(this); findViewById(R.id.bApplyText).setOnClickListener(this); ((ImageButton) findViewById(R.id.bStroke)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setSelected(!v.isSelected()); } }); lineWidthListener = new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub if (true || fromUser) { /*dWidth = (progress/10); drawView.setWidth((dWidth+1)*5);*/ dWidth = progress; drawView.setWidth(dWidth); Editor e = prefs.edit(); e.putInt("dWidth", dWidth); e.commit(); } } }; ((SeekBar) findViewById(R.id.seekBarLine)).setOnSeekBarChangeListener(lineWidthListener); ((SeekBar) findViewById(R.id.ls_seekBarLine)).setOnSeekBarChangeListener(lineWidthListener); fontSizeListener = new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub if (fromUser) { fWidth = progress / 10; int c = 40 + fWidth * 20; drawView.setFontSize(c); Editor e = prefs.edit(); e.putInt("fWidth", fWidth); e.commit(); try { ((TextView) findViewById(R.id.tvTextType)).setText(String.format("%d", c)); ((TextView) findViewById(R.id.ls_tvTextType)).setText(String.format("%d", c)); } catch (Exception ex) { } } } }; ((SeekBar) findViewById(R.id.seekBarType)).setOnSeekBarChangeListener(fontSizeListener); ((SeekBar) findViewById(R.id.ls_seekBarType)).setOnSeekBarChangeListener(fontSizeListener); drawView = (DrawView) findViewById(R.id.painter); drawView.setWidth((dWidth + 1) * 5); drawView.setFontSize(40 + fWidth * 20); setBarConfig(getResources().getConfiguration().orientation); findViewById(R.id.bEditPage).setOnClickListener(this); findViewById(R.id.bToolColor).setOnClickListener(this); findViewById(R.id.bErase).setOnClickListener(this); findViewById(R.id.bToolShape).setOnClickListener(this); findViewById(R.id.bToolText).setOnClickListener(this); findViewById(R.id.bToolCrop).setOnClickListener(this); findViewById(R.id.btnBack).setOnClickListener(this); findViewById(R.id.bDone).setOnClickListener(this); findViewById(R.id.btnShare).setOnClickListener(this); findViewById(R.id.bSave2SD).setOnClickListener(this); findViewById(R.id.bSave2Nimbus).setOnClickListener(this); userMail = prefs.getString("userMail", ""); userPass = prefs.getString("userPass", ""); sessionId = prefs.getString("sessionId", ""); appSettings.sessionId = sessionId; appSettings.userMail = userMail; appSettings.userPass = userPass; storePath = ""; Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); //storePath= intent.getPackage().getClass().toString(); if ((Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SEND.equals(action) || "com.onebit.nimbusnote.EDIT_PHOTO".equals(action)) && type != null) { if (type.startsWith("image/")) { Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri == null) imageUri = intent.getData(); if (imageUri != null) { String url = Uri.decode(imageUri.toString()); if (url.startsWith(CONTENT_PHOTOS_URI_PREFIX)) { url = getPhotosPhotoLink(url); } //else url=Uri.decode(url); ContentResolver cr = getContentResolver(); InputStream is; try { is = cr.openInputStream(Uri.parse(url)); if ("com.onebit.nimbusnote.EDIT_PHOTO".equals(action)) storePath = " ";//getGalleryPath(Uri.parse(url)); Bitmap bmp = BitmapFactory.decodeStream(is); if (bmp.getWidth() != -1 && bmp.getHeight() != -1) drawView.setBitmap(bmp, 0); } catch (Exception e) { appSettings.appendLog("paint:onCreate " + e.getMessage()); } } } } else { String act = getIntent().getExtras().getString("act"); if ("photo".equals(act)) { getPhoto(); } else if ("picture".equals(act)) { getPicture(); } else { String filePath = getIntent().getExtras().getString("path"); boolean isTemp = getIntent().getExtras().getBoolean("temp"); domain = getIntent().getExtras().getString("domain"); if (domain == null) domain = serverHelper.getDate(); if (filePath.contains("://")) { Bitmap bmp = helper.LoadImageFromWeb(filePath); if (bmp != null) { drawView.setBitmap(bmp, 0); } } else { File file = new File(filePath); if (file.exists()) { try { int orient = helper.getOrientationFromExif(filePath); Bitmap bmp = helper.decodeSampledBitmap(filePath, 1000, 1000); if (bmp != null) { drawView.setBitmap(bmp, orient); } } catch (Exception e) { appSettings.appendLog("paint.onCreate() " + e.getMessage()); } if (isTemp) file.delete(); } } } } drawView.setBackgroundColor(Color.WHITE); drawView.requestFocus(); drawView.setColour(dColor); setPaletteColor(dColor); drawView.setSelChangeListener(new shapeSelectionListener() { @Override public void onSelectionChanged(int shSize, int fSize, int shColor) { setSelectedFoot(0); setLandToolSelected(R.id.bEditPage_land); //updateColorDialog(shSize!=-1?(shSize/5)-1:dWidth, fSize!=-1?(fSize-40)/20:fWidth, shColor!=0?colorToId(shColor):dColor); dColor = shColor; ccolor = shColor; int sw = shSize != -1 ? shSize : dWidth; canChange = false; ((SeekBar) findViewById(R.id.seekBarLine)).setProgress(sw); ((SeekBar) findViewById(R.id.ls_seekBarLine)).setProgress(sw); setPaletteColor(dColor); drawView.setColour(dColor); canChange = true; } @Override public void onTextChanged(String text, boolean stroke) { if (findViewById(R.id.text_field).getVisibility() != View.VISIBLE) { hideTools(); findViewById(R.id.bStroke).setSelected(stroke); ((EditText) findViewById(R.id.etEditorText)).setText(text); findViewById(R.id.text_field).setVisibility(View.VISIBLE); findViewById(R.id.etEditorText).requestFocus(); ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) .showSoftInput(findViewById(R.id.etEditorText), 0); findViewById(R.id.bToolText).postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub setSelectedFoot(2); } }, 100); } } }); setColorButtons(dColor); //mPlanetTitles = getResources().getStringArray(R.array.lmenu_paint); /*ListView listView = (ListView) findViewById(R.id.left_drawer); listView.setAdapter(new DrawerMenuAdapter(this,getResources().getStringArray(R.array.lmenu_paint))); listView.setOnItemClickListener(this);*/ }
From source file:com.mobicage.rogerthat.util.ui.SendMessageView.java
private void copyImageFile(final Uri selectedImage) { final ContentResolver cr = mActivity.getContentResolver(); final ProgressDialog progressDialog = showProcessing(); new SafeAsyncTask<Object, Object, Boolean>() { @Override/*from w w w . j a v a2 s.com*/ protected Boolean safeDoInBackground(Object... params) { L.d("Processing picture: " + selectedImage.toString()); try { String fileType = cr.getType(selectedImage); L.d("fileType: " + fileType); if (fileType == null || AttachmentViewerActivity.CONTENT_TYPE_JPEG.equalsIgnoreCase(fileType)) { mUploadFileExtenstion = AttachmentViewerActivity.CONTENT_TYPE_JPEG; } else { mUploadFileExtenstion = AttachmentViewerActivity.CONTENT_TYPE_JPEG; } if (mTmpUploadFile.getAbsolutePath().equals(selectedImage.getPath())) { return true; } else { InputStream is = cr.openInputStream(selectedImage); if (is != null) { try { OutputStream out = new FileOutputStream(mTmpUploadFile); try { IOUtils.copy(is, out, 1024); } finally { out.close(); } } finally { is.close(); } return true; } } } catch (FileNotFoundException e) { L.d(e); } catch (Exception e) { L.bug("Unknown exception occured while processing picture: " + selectedImage.toString(), e); } return false; }; @Override protected void safeOnPostExecute(Boolean result) { progressDialog.dismiss(); if (result) { setPictureSelected(); } else { UIUtils.showLongToast(mActivity, mActivity.getString(R.string.error_please_try_again)); } } @Override protected void safeOnCancelled(Boolean result) { } @Override protected void safeOnProgressUpdate(Object... values) { } @Override protected void safeOnPreExecute() { }; }.execute(); }
From source file:com.keylesspalace.tusky.activity.ComposeActivity.java
private void pickMedia(Uri uri, long mediaSize) { ContentResolver contentResolver = getContentResolver(); if (mediaSize == MEDIA_SIZE_UNKNOWN) { displayTransientError(R.string.error_media_upload_opening); return;// w w w. ja v a 2 s . c o m } String mimeType = contentResolver.getType(uri); if (mimeType != null) { String topLevelType = mimeType.substring(0, mimeType.indexOf('/')); switch (topLevelType) { case "video": { if (mediaSize > STATUS_MEDIA_SIZE_LIMIT) { displayTransientError(R.string.error_media_upload_size); return; } if (mediaQueued.size() > 0 && mediaQueued.get(0).type == QueuedMedia.Type.IMAGE) { displayTransientError(R.string.error_media_upload_image_or_video); return; } MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(this, uri); Bitmap source = retriever.getFrameAtTime(); Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, 128, 128); source.recycle(); addMediaToQueue(QueuedMedia.Type.VIDEO, bitmap, uri, mediaSize); break; } case "image": { InputStream stream; try { stream = contentResolver.openInputStream(uri); } catch (FileNotFoundException e) { displayTransientError(R.string.error_media_upload_opening); return; } Bitmap source = BitmapFactory.decodeStream(stream); Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, 128, 128); source.recycle(); try { if (stream != null) { stream.close(); } } catch (IOException e) { bitmap.recycle(); displayTransientError(R.string.error_media_upload_opening); return; } addMediaToQueue(QueuedMedia.Type.IMAGE, bitmap, uri, mediaSize); break; } default: { displayTransientError(R.string.error_media_upload_type); break; } } } else { displayTransientError(R.string.error_media_upload_type); } }
From source file:org.rm3l.ddwrt.mgmt.AbstractRouterMgmtDialogFragment.java
/** * Receive the result from a previous call to * {@link #startActivityForResult(android.content.Intent, int)}. This follows the * related Activity API as described there in * {@link android.app.Activity#onActivityResult(int, int, android.content.Intent)}. * * @param requestCode The integer request code originally supplied to * startActivityForResult(), allowing you to identify who this * result came from./*from w w w . j av a 2 s .co m*/ * @param resultCode The integer result code returned by the child activity * through its setResult(). * @param resultData An Intent, which can return result data to the caller */ @Override public void onActivityResult(int requestCode, int resultCode, Intent resultData) { // The ACTION_OPEN_DOCUMENT intent was sent with the request code // READ_REQUEST_CODE. If the request code seen here doesn't match, it's the // response to some other intent, and the code below shouldn't run at all. if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) { // The document selected by the user won't be returned in the intent. // Instead, a URI to that document will be contained in the return intent // provided to this method as a parameter. // Pull that URI using resultData.getData(). Uri uri; if (resultData != null) { uri = resultData.getData(); Log.i(LOG_TAG, "Uri: " + uri.toString()); final AlertDialog d = (AlertDialog) getDialog(); if (d != null) { final ContentResolver contentResolver = this.getSherlockActivity().getContentResolver(); final Cursor uriCursor = contentResolver.query(uri, null, null, null, null); /* * Get the column indexes of the data in the Cursor, * move to the first row in the Cursor, get the data, * and display it. */ final int nameIndex = uriCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); final int sizeIndex = uriCursor.getColumnIndex(OpenableColumns.SIZE); uriCursor.moveToFirst(); //File size in bytes final long fileSize = uriCursor.getLong(sizeIndex); final String filename = uriCursor.getString(nameIndex); //Check file size if (fileSize > MAX_PRIVKEY_SIZE_BYTES) { displayMessage(String.format("File '%s' too big (%s). Limit is %s", filename, toHumanReadableByteCount(fileSize), toHumanReadableByteCount(MAX_PRIVKEY_SIZE_BYTES)), ALERT); return; } //Replace button hint message with file name final Button fileSelectorButton = (Button) d.findViewById(R.id.router_add_privkey); final CharSequence fileSelectorOriginalHint = fileSelectorButton.getHint(); if (!Strings.isNullOrEmpty(filename)) { fileSelectorButton.setHint(filename); } //Set file actual content in hidden field final TextView privKeyPath = (TextView) d.findViewById(R.id.router_add_privkey_path); try { privKeyPath.setText(IOUtils.toString(contentResolver.openInputStream(uri))); } catch (IOException e) { displayMessage("Error: " + e.getMessage(), ALERT); e.printStackTrace(); fileSelectorButton.setHint(fileSelectorOriginalHint); } } } } }
From source file:com.fa.mastodon.activity.ComposeActivity.java
private void pickMedia(Uri uri, long mediaSize) { ContentResolver contentResolver = getContentResolver(); if (mediaSize == MEDIA_SIZE_UNKNOWN) { displayTransientError(R.string.error_media_upload_opening); return;//from w w w . j a v a2 s. c o m } String mimeType = contentResolver.getType(uri); if (mimeType != null) { String topLevelType = mimeType.substring(0, mimeType.indexOf('/')); switch (topLevelType) { case "video": { if (mediaSize > STATUS_MEDIA_SIZE_LIMIT) { displayTransientError(R.string.error_media_upload_size); return; } if (mediaQueued.size() > 0 && mediaQueued.get(0).type == QueuedMedia.Type.IMAGE) { displayTransientError(R.string.error_media_upload_image_or_video); return; } MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(this, uri); Bitmap source = retriever.getFrameAtTime(); Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, THUMBNAIL_SIZE, THUMBNAIL_SIZE); source.recycle(); addMediaToQueue(QueuedMedia.Type.VIDEO, bitmap, uri, mediaSize); break; } case "image": { InputStream stream; try { stream = contentResolver.openInputStream(uri); } catch (FileNotFoundException e) { displayTransientError(R.string.error_media_upload_opening); return; } Bitmap source = BitmapFactory.decodeStream(stream); Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, THUMBNAIL_SIZE, THUMBNAIL_SIZE); source.recycle(); try { if (stream != null) { stream.close(); } } catch (IOException e) { bitmap.recycle(); displayTransientError(R.string.error_media_upload_opening); return; } addMediaToQueue(QueuedMedia.Type.IMAGE, bitmap, uri, mediaSize); break; } default: { displayTransientError(R.string.error_media_upload_type); break; } } } else { displayTransientError(R.string.error_media_upload_type); } }
From source file:com.fvd.nimbus.PaintActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { ContentResolver cr; InputStream is;//from w w w . ja va 2 s .c o m if (requestCode == TAKE_PHOTO) { showProgress(false); if (resultCode == -1) { try { if (data != null) { if (data.hasExtra("data")) { //Bitmap bm = ; drawView.setVisibility(View.INVISIBLE); drawView.recycle(); drawView.setBitmap((Bitmap) data.getParcelableExtra("data"), 0); drawView.setVisibility(View.VISIBLE); } } else { if (outputFileUri != null) { cr = getContentResolver(); try { is = cr.openInputStream(outputFileUri); Bitmap bmp = BitmapFactory.decodeStream(is); if (bmp.getWidth() != -1 && bmp.getHeight() != -1) { drawView.setVisibility(View.INVISIBLE); drawView.recycle(); drawView.setBitmap(bmp, 0); drawView.setVisibility(View.VISIBLE); } } catch (Exception e) { appSettings.appendLog("paint:onCreate " + e.getMessage()); } } } } catch (Exception e) { appSettings.appendLog("main:onActivityResult: exception - " + e.getMessage()); } } ((ViewAnimator) findViewById(R.id.top_switcher)).setDisplayedChild(0); } else if (requestCode == TAKE_PICTURE) { showProgress(false); if (resultCode == -1 && data != null) { boolean temp = false; try { Uri resultUri = data.getData(); String drawString = resultUri.getPath(); InputStream input = getContentResolver().openInputStream(resultUri); drawView.setVisibility(View.INVISIBLE); drawView.recycle(); drawView.setBitmap(BitmapFactory.decodeStream(input), 0); //drawView.forceRedraw(); drawView.setVisibility(View.VISIBLE); } catch (Exception e) { appSettings.appendLog("main:onActivityResult " + e.getMessage()); } } ((ViewAnimator) findViewById(R.id.top_switcher)).setDisplayedChild(0); } else if (requestCode == SHOW_SETTINGS) { switch (resultCode) { case RESULT_FIRST_USER + 1: Intent i = new Intent(getApplicationContext(), PrefsActivity.class); startActivity(i); //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up ); overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out); break; case RESULT_FIRST_USER + 2: if (appSettings.sessionId.length() == 0) showLogin(); else { appSettings.sessionId = ""; //serverHelper.getInstance().setSessionId(appSettings.sessionId); Editor e = prefs.edit(); e.putString("userMail", userMail); e.putString("userPass", ""); e.putString("sessionId", appSettings.sessionId); e.commit(); showLogin(); } break; case RESULT_FIRST_USER + 3: try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getApplicationInfo().packageName))); } catch (Exception e) { } case RESULT_FIRST_USER + 4: Uri uri = Uri.parse( "http://help.everhelper.me/customer/portal/articles/1376820-nimbus-clipper-for-android---quick-guide"); Intent it = new Intent(Intent.ACTION_VIEW, uri); startActivity(it); //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up ); overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out); break; case RESULT_FIRST_USER + 5: final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); alertDialogBuilder.setMessage(getScriptContent("license.txt")).setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // no alert dialog shown //alertDialogShown = null; // canceled setResult(RESULT_CANCELED); // and finish //finish(); } }); // create alert dialog final AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.setTitle(getString(R.string.license_title)); // and show //alertDialogShown = alertDialog; try { alertDialog.show(); } catch (final java.lang.Exception e) { // nothing to do } catch (final java.lang.Error e) { // nothing to do } break; default: break; } } if (requestCode == 3) { if (resultCode == RESULT_OK || resultCode == RESULT_FIRST_USER) { userMail = data.getStringExtra("userMail"); userPass = data.getStringExtra("userPass"); if (resultCode == RESULT_OK) sendRequest("user:auth", String.format("\"email\":\"%s\",\"password\":\"%s\"", userMail, userPass)); else serverHelper.getInstance().sendOldRequest("user_register", String.format( "{\"action\": \"user_register\",\"email\":\"%s\",\"password\":\"%s\",\"_client_software\": \"ff_addon\"}", userMail, userPass), ""); } } else if (requestCode == 11) { if (appSettings.sessionId != "") { sessionId = appSettings.sessionId; userPass = appSettings.userPass; sendShot(); } } else if (requestCode == 4) { if (resultCode == RESULT_OK) { String id = data.getStringExtra("id").toString(); serverHelper.getInstance().shareShot(id); } } else if (resultCode == RESULT_OK) { drawView.setColour(dColor); setPaletteColor(dColor); Uri resultUri = data.getData(); String drawString = resultUri.getPath(); String galleryString = getGalleryPath(resultUri); if (galleryString != null) { drawString = galleryString; } // else another file manager was used else { if (drawString.contains("//")) { drawString = drawString.substring(drawString.lastIndexOf("//")); } } // set the background to the selected picture if (drawString.length() > 0) { Drawable drawBackground = Drawable.createFromPath(drawString); drawView.setBackgroundDrawable(drawBackground); } } }
From source file:org.cafemember.ui.LaunchActivity.java
private boolean handleIntent(Intent intent, boolean isNew, boolean restore, boolean fromPassword) { int flags = intent.getFlags(); if (!fromPassword && (AndroidUtilities.needShowPasscode(true) || UserConfig.isWaitingForPasscodeEnter)) { showPasscodeActivity();//w w w . j av a 2 s .co m passcodeSaveIntent = intent; passcodeSaveIntentIsNew = isNew; passcodeSaveIntentIsRestore = restore; UserConfig.saveConfig(false); } else { boolean pushOpened = false; Integer push_user_id = 0; Integer push_chat_id = 0; Integer push_enc_id = 0; Integer open_settings = 0; long dialogId = intent != null && intent.getExtras() != null ? intent.getExtras().getLong("dialogId", 0) : 0; boolean showDialogsList = false; boolean showPlayer = false; photoPathsArray = null; videoPath = null; sendingText = null; documentsPathsArray = null; documentsOriginalPathsArray = null; documentsMimeType = null; documentsUrisArray = null; contactsToSend = null; if (UserConfig.isClientActivated() && (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) { if (intent != null && intent.getAction() != null && !restore) { if (Intent.ACTION_SEND.equals(intent.getAction())) { boolean error = false; String type = intent.getType(); if (type != null && type.equals(ContactsContract.Contacts.CONTENT_VCARD_TYPE)) { try { Uri uri = (Uri) intent.getExtras().get(Intent.EXTRA_STREAM); if (uri != null) { ContentResolver cr = getContentResolver(); InputStream stream = cr.openInputStream(uri); String name = null; String nameEncoding = null; String nameCharset = null; ArrayList<String> phones = new ArrayList<>(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(stream, "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { String[] args = line.split(":"); if (args.length != 2) { continue; } if (args[0].startsWith("FN")) { String[] params = args[0].split(";"); for (String param : params) { String[] args2 = param.split("="); if (args2.length != 2) { continue; } if (args2[0].equals("CHARSET")) { nameCharset = args2[1]; } else if (args2[0].equals("ENCODING")) { nameEncoding = args2[1]; } } name = args[1]; if (nameEncoding != null && nameEncoding.equalsIgnoreCase("QUOTED-PRINTABLE")) { while (name.endsWith("=") && nameEncoding != null) { name = name.substring(0, name.length() - 1); line = bufferedReader.readLine(); if (line == null) { break; } name += line; } byte[] bytes = AndroidUtilities .decodeQuotedPrintable(name.getBytes()); if (bytes != null && bytes.length != 0) { String decodedName = new String(bytes, nameCharset); if (decodedName != null) { name = decodedName; } } } } else if (args[0].startsWith("TEL")) { String phone = PhoneFormat.stripExceptNumbers(args[1], true); if (phone.length() > 0) { phones.add(phone); } } } try { bufferedReader.close(); stream.close(); } catch (Exception e) { FileLog.e("tmessages", e); } if (name != null && !phones.isEmpty()) { contactsToSend = new ArrayList<>(); for (String phone : phones) { TLRPC.User user = new TLRPC.TL_userContact_old2(); user.phone = phone; user.first_name = name; user.last_name = ""; user.id = 0; contactsToSend.add(user); } } } else { error = true; } } catch (Exception e) { FileLog.e("tmessages", e); error = true; } } else { String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (text == null) { CharSequence textSequence = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); if (textSequence != null) { text = textSequence.toString(); } } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); if (text != null && text.length() != 0) { if ((text.startsWith("http://") || text.startsWith("https://")) && subject != null && subject.length() != 0) { text = subject + "\n" + text; } sendingText = text; } else if (subject != null && subject.length() > 0) { sendingText = subject; } Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (parcelable != null) { String path; if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } Uri uri = (Uri) parcelable; if (uri != null) { if (isInternalUri(uri)) { error = true; } } if (!error) { if (uri != null && (type != null && type.startsWith("image/") || uri.toString().toLowerCase().endsWith(".jpg"))) { if (photoPathsArray == null) { photoPathsArray = new ArrayList<>(); } photoPathsArray.add(uri); } else { path = AndroidUtilities.getPath(uri); if (path != null) { if (path.startsWith("file:")) { path = path.replace("file://", ""); } if (type != null && type.startsWith("video/")) { videoPath = path; } else { if (documentsPathsArray == null) { documentsPathsArray = new ArrayList<>(); documentsOriginalPathsArray = new ArrayList<>(); } documentsPathsArray.add(path); documentsOriginalPathsArray.add(uri.toString()); } } else { if (documentsUrisArray == null) { documentsUrisArray = new ArrayList<>(); } documentsUrisArray.add(uri); documentsMimeType = type; } } if (sendingText != null) { if (sendingText.contains("WhatsApp")) { //remove unnecessary caption 'sent from WhatsApp' from photos forwarded from WhatsApp sendingText = null; } } } } else if (sendingText == null) { error = true; } } if (error) { Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show(); } } else if (intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) { boolean error = false; try { ArrayList<Parcelable> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); String type = intent.getType(); if (uris != null) { for (int a = 0; a < uris.size(); a++) { Parcelable parcelable = uris.get(a); if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } Uri uri = (Uri) parcelable; if (uri != null) { if (isInternalUri(uri)) { uris.remove(a); a--; } } } if (uris.isEmpty()) { uris = null; } } if (uris != null) { if (type != null && type.startsWith("image/")) { for (int a = 0; a < uris.size(); a++) { Parcelable parcelable = uris.get(a); if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } Uri uri = (Uri) parcelable; if (photoPathsArray == null) { photoPathsArray = new ArrayList<>(); } photoPathsArray.add(uri); } } else { for (int a = 0; a < uris.size(); a++) { Parcelable parcelable = uris.get(a); if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } String path = AndroidUtilities.getPath((Uri) parcelable); String originalPath = parcelable.toString(); if (originalPath == null) { originalPath = path; } if (path != null) { if (path.startsWith("file:")) { path = path.replace("file://", ""); } if (documentsPathsArray == null) { documentsPathsArray = new ArrayList<>(); documentsOriginalPathsArray = new ArrayList<>(); } documentsPathsArray.add(path); documentsOriginalPathsArray.add(originalPath); } } } } else { error = true; } } catch (Exception e) { FileLog.e("tmessages", e); error = true; } if (error) { Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show(); } } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { Uri data = intent.getData(); if (data != null) { String username = null; String group = null; String sticker = null; String botUser = null; String botChat = null; String message = null; Integer messageId = null; boolean hasUrl = false; String scheme = data.getScheme(); if (scheme != null) { if ((scheme.equals("http") || scheme.equals("https"))) { String host = data.getHost().toLowerCase(); if (host.equals("telegram.me") || host.equals("telegram.dog")) { String path = data.getPath(); if (path != null && path.length() > 1) { path = path.substring(1); if (path.startsWith("joinchat/")) { group = path.replace("joinchat/", ""); } else if (path.startsWith("addstickers/")) { sticker = path.replace("addstickers/", ""); } else if (path.startsWith("msg/") || path.startsWith("share/")) { message = data.getQueryParameter("url"); if (message == null) { message = ""; } if (data.getQueryParameter("text") != null) { if (message.length() > 0) { hasUrl = true; message += "\n"; } message += data.getQueryParameter("text"); } } else if (path.length() >= 1) { List<String> segments = data.getPathSegments(); if (segments.size() > 0) { username = segments.get(0); if (segments.size() > 1) { messageId = Utilities.parseInt(segments.get(1)); if (messageId == 0) { messageId = null; } } } botUser = data.getQueryParameter("start"); botChat = data.getQueryParameter("startgroup"); } } } } else if (scheme.equals("tg")) { String url = data.toString(); if (url.startsWith("tg:resolve") || url.startsWith("tg://resolve")) { url = url.replace("tg:resolve", "tg://telegram.org").replace("tg://resolve", "tg://telegram.org"); data = Uri.parse(url); username = data.getQueryParameter("domain"); botUser = data.getQueryParameter("start"); botChat = data.getQueryParameter("startgroup"); } else if (url.startsWith("tg:join") || url.startsWith("tg://join")) { url = url.replace("tg:join", "tg://telegram.org").replace("tg://join", "tg://telegram.org"); data = Uri.parse(url); group = data.getQueryParameter("invite"); } else if (url.startsWith("tg:addstickers") || url.startsWith("tg://addstickers")) { url = url.replace("tg:addstickers", "tg://telegram.org") .replace("tg://addstickers", "tg://telegram.org"); data = Uri.parse(url); sticker = data.getQueryParameter("set"); } else if (url.startsWith("tg:msg") || url.startsWith("tg://msg") || url.startsWith("tg://share") || url.startsWith("tg:share")) { url = url.replace("tg:msg", "tg://telegram.org") .replace("tg://msg", "tg://telegram.org") .replace("tg://share", "tg://telegram.org") .replace("tg:share", "tg://telegram.org"); data = Uri.parse(url); message = data.getQueryParameter("url"); if (message == null) { message = ""; } if (data.getQueryParameter("text") != null) { if (message.length() > 0) { hasUrl = true; message += "\n"; } message += data.getQueryParameter("text"); } } } } if (username != null || group != null || sticker != null || message != null) { runLinkRequest(username, group, sticker, botUser, botChat, message, hasUrl, messageId, 0); } else { try { Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int userId = cursor.getInt(cursor.getColumnIndex("DATA4")); NotificationCenter.getInstance() .postNotificationName(NotificationCenter.closeChats); push_user_id = userId; } cursor.close(); } } catch (Exception e) { FileLog.e("tmessages", e); } } } } else if (intent.getAction().equals("org.telegram.messenger.OPEN_ACCOUNT")) { open_settings = 1; } else if (intent.getAction().startsWith("com.tmessages.openchat")) { int chatId = intent.getIntExtra("chatId", 0); int userId = intent.getIntExtra("userId", 0); int encId = intent.getIntExtra("encId", 0); if (chatId != 0) { NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); push_chat_id = chatId; } else if (userId != 0) { NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); push_user_id = userId; } else if (encId != 0) { NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); push_enc_id = encId; } else { showDialogsList = true; } } else if (intent.getAction().equals("com.tmessages.openplayer")) { showPlayer = true; } } } if (push_user_id != 0) { Bundle args = new Bundle(); args.putInt("user_id", push_user_id); if (mainFragmentsStack.isEmpty() || MessagesController.checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) { ChatActivity fragment = new ChatActivity(args); if (actionBarLayout.presentFragment(fragment, false, true, true)) { pushOpened = true; } } } else if (push_chat_id != 0) { Bundle args = new Bundle(); args.putInt("chat_id", push_chat_id); if (mainFragmentsStack.isEmpty() || MessagesController.checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) { ChatActivity fragment = new ChatActivity(args); if (actionBarLayout.presentFragment(fragment, false, true, true)) { pushOpened = true; } } } else if (push_enc_id != 0) { Bundle args = new Bundle(); args.putInt("enc_id", push_enc_id); ChatActivity fragment = new ChatActivity(args); if (actionBarLayout.presentFragment(fragment, false, true, true)) { pushOpened = true; } } else if (showDialogsList) { if (!AndroidUtilities.isTablet()) { actionBarLayout.removeAllFragments(); } else { if (!layersActionBarLayout.fragmentsStack.isEmpty()) { for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) { layersActionBarLayout .removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0)); a--; } layersActionBarLayout.closeLastFragment(false); } } pushOpened = false; isNew = false; } else if (showPlayer) { if (AndroidUtilities.isTablet()) { for (int a = 0; a < layersActionBarLayout.fragmentsStack.size(); a++) { BaseFragment fragment = layersActionBarLayout.fragmentsStack.get(a); if (fragment instanceof AudioPlayerActivity) { layersActionBarLayout.removeFragmentFromStack(fragment); break; } } actionBarLayout.showLastFragment(); rightActionBarLayout.showLastFragment(); drawerLayoutContainer.setAllowOpenDrawer(false, false); } else { for (int a = 0; a < actionBarLayout.fragmentsStack.size(); a++) { BaseFragment fragment = actionBarLayout.fragmentsStack.get(a); if (fragment instanceof AudioPlayerActivity) { actionBarLayout.removeFragmentFromStack(fragment); break; } } drawerLayoutContainer.setAllowOpenDrawer(true, false); } actionBarLayout.presentFragment(new AudioPlayerActivity(), false, true, true); pushOpened = true; } else if (videoPath != null || photoPathsArray != null || sendingText != null || documentsPathsArray != null || contactsToSend != null || documentsUrisArray != null) { if (!AndroidUtilities.isTablet()) { NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); } if (dialogId == 0) { Bundle args = new Bundle(); args.putBoolean("onlySelect", true); if (contactsToSend != null) { args.putString("selectAlertString", LocaleController.getString("SendContactTo", R.string.SendMessagesTo)); args.putString("selectAlertStringGroup", LocaleController.getString("SendContactToGroup", R.string.SendContactToGroup)); } else { args.putString("selectAlertString", LocaleController.getString("SendMessagesTo", R.string.SendMessagesTo)); args.putString("selectAlertStringGroup", LocaleController.getString("SendMessagesToGroup", R.string.SendMessagesToGroup)); } DialogsActivity fragment = new DialogsActivity(args); dialogsFragment = fragment; fragment.setDelegate(this); boolean removeLast; if (AndroidUtilities.isTablet()) { removeLast = layersActionBarLayout.fragmentsStack.size() > 0 && layersActionBarLayout.fragmentsStack.get( layersActionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity; } else { removeLast = actionBarLayout.fragmentsStack.size() > 1 && actionBarLayout.fragmentsStack .get(actionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity; } actionBarLayout.presentFragment(fragment, removeLast, true, true); pushOpened = true; if (PhotoViewer.getInstance().isVisible()) { PhotoViewer.getInstance().closePhoto(false, true); } drawerLayoutContainer.setAllowOpenDrawer(false, false); if (AndroidUtilities.isTablet()) { actionBarLayout.showLastFragment(); rightActionBarLayout.showLastFragment(); } else { drawerLayoutContainer.setAllowOpenDrawer(true, false); } } else { didSelectDialog(null, dialogId, false); } } else if (open_settings != 0) { actionBarLayout.presentFragment(new SettingsActivity(), false, true, true); if (AndroidUtilities.isTablet()) { actionBarLayout.showLastFragment(); rightActionBarLayout.showLastFragment(); drawerLayoutContainer.setAllowOpenDrawer(false, false); } else { drawerLayoutContainer.setAllowOpenDrawer(true, false); } pushOpened = true; } if (!pushOpened && !isNew) { if (AndroidUtilities.isTablet()) { if (!UserConfig.isClientActivated()) { if (layersActionBarLayout.fragmentsStack.isEmpty()) { layersActionBarLayout.addFragmentToStack(new LoginActivity()); drawerLayoutContainer.setAllowOpenDrawer(false, false); } } else { if (actionBarLayout.fragmentsStack.isEmpty()) { actionBarLayout.addFragmentToStack(new DialogsActivity(null)); drawerLayoutContainer.setAllowOpenDrawer(true, false); } } } else { if (actionBarLayout.fragmentsStack.isEmpty()) { if (!UserConfig.isClientActivated()) { actionBarLayout.addFragmentToStack(new LoginActivity()); drawerLayoutContainer.setAllowOpenDrawer(false, false); } else { actionBarLayout.addFragmentToStack(new DialogsActivity(null)); drawerLayoutContainer.setAllowOpenDrawer(true, false); } } } actionBarLayout.showLastFragment(); if (AndroidUtilities.isTablet()) { layersActionBarLayout.showLastFragment(); rightActionBarLayout.showLastFragment(); } } intent.setAction(null); return pushOpened; } return false; }