List of usage examples for android.content Intent getStringArrayExtra
public String[] getStringArrayExtra(String name)
From source file:dev.dworks.apps.anexplorer.DocumentsActivity.java
private void buildDefaultState() { mState = new State(); final Intent intent = getIntent(); final String action = intent.getAction(); if (IntentUtils.ACTION_OPEN_DOCUMENT.equals(action)) { mState.action = ACTION_OPEN;//from ww w .j a va 2 s . co m } else if (IntentUtils.ACTION_CREATE_DOCUMENT.equals(action)) { mState.action = ACTION_CREATE; } else if (Intent.ACTION_GET_CONTENT.equals(action)) { mState.action = ACTION_GET_CONTENT; } else if (DocumentsContract.ACTION_MANAGE_ROOT.equals(action)) { //mState.action = ACTION_MANAGE; mState.action = ACTION_BROWSE; } else { mState.action = ACTION_BROWSE; } if (mState.action == ACTION_OPEN || mState.action == ACTION_GET_CONTENT) { mState.allowMultiple = intent.getBooleanExtra(IntentUtils.EXTRA_ALLOW_MULTIPLE, false); } if (mState.action == ACTION_GET_CONTENT || mState.action == ACTION_BROWSE) { mState.acceptMimes = new String[] { "*/*" }; mState.allowMultiple = true; } else if (intent.hasExtra(IntentUtils.EXTRA_MIME_TYPES)) { mState.acceptMimes = intent.getStringArrayExtra(IntentUtils.EXTRA_MIME_TYPES); } else { mState.acceptMimes = new String[] { intent.getType() }; } mState.localOnly = intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, true); mState.forceAdvanced = intent.getBooleanExtra(DocumentsContract.EXTRA_SHOW_ADVANCED, false); mState.showAdvanced = mState.forceAdvanced | SettingsActivity.getDisplayAdvancedDevices(this); mState.rootMode = SettingsActivity.getRootMode(this); }
From source file:org.mariotaku.twidere.activity.support.ComposeActivity.java
private boolean handleIntent(final Intent intent) { final String action = intent.getAction(); if (action == null) return false; mShouldSaveAccounts = false;//from w w w. j a v a 2s .c o m mMentionUser = intent.getParcelableExtra(EXTRA_USER); mInReplyToStatus = intent.getParcelableExtra(EXTRA_STATUS); mInReplyToStatusId = mInReplyToStatus != null ? mInReplyToStatus.id : -1; switch (action) { case INTENT_ACTION_REPLY: { return handleReplyIntent(mInReplyToStatus); } case INTENT_ACTION_QUOTE: { return handleQuoteIntent(mInReplyToStatus); } case INTENT_ACTION_EDIT_DRAFT: { mDraftItem = intent.getParcelableExtra(EXTRA_DRAFT); return handleEditDraftIntent(mDraftItem); } case INTENT_ACTION_MENTION: { return handleMentionIntent(mMentionUser); } case INTENT_ACTION_REPLY_MULTIPLE: { final String[] screenNames = intent.getStringArrayExtra(EXTRA_SCREEN_NAMES); final long accountId = intent.getLongExtra(EXTRA_ACCOUNT_ID, -1); final long inReplyToUserId = intent.getLongExtra(EXTRA_IN_REPLY_TO_ID, -1); return handleReplyMultipleIntent(screenNames, accountId, inReplyToUserId); } case INTENT_ACTION_COMPOSE_TAKE_PHOTO: { return takePhoto(); } case INTENT_ACTION_COMPOSE_PICK_IMAGE: { return pickImage(); } } // Unknown action or no intent extras return false; }
From source file:com.free.searcher.MainFragment.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d("data", "" + data); Log.d("requestCode", "" + requestCode); Log.d("resultCode", "" + resultCode); locX = 0;//from w w w . j av a 2 s.c o m locY = 0; try { if (data != null) { String[] stringExtra = data.getStringArrayExtra(FolderChooserActivity.SELECTED_DIR); if (requestCode == SEARCH_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { stopReadAndSearch(); Log.d("SEARCH_REQUEST_CODE.selectedFiles", Util.arrayToString(stringExtra, true, MainFragment.LINE_SEP)); currentZipFileName = ""; // lm du kh?i show web getSourceFile selectedFiles = stringExtra; getSourceFileTask = new GetSourceFileTask(MainFragment.this); getSourceFileTask.execute(); load = "Search"; } else { // RESULT_CANCEL if (selectedFiles.length == 0) { showToast("Nothing to search"); statusView.setText("Nothing to search"); } } } else if (requestCode == ZIP_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { stopReadAndSearch(); currentZipFileName = stringExtra[0]; selectedFiles = stringExtra; load = "Zip Reader"; Log.d("ZIP_REQUEST_CODE.currentZFile", currentZipFileName); statusView.setText("reading " + currentZipFileName + "..."); try { zr = new ZipReadingTask(MainFragment.this); zr.execute(); } catch (Exception e) { statusView.setText(e.getMessage()); Log.d("zip result", e.getMessage(), e); showToast(e.getMessage()); } } else if (currentZipFileName.length() == 0) { showToast("Nothing to read"); statusView.setText("Nothing to read"); } // } else if (requestCode == COMPARE_REQUEST_CODE1) { // if (resultCode == Activity.RESULT_OK) { // oriDoc = stringExtra[0]; // Log.d("COMPARE_REQUEST_CODE1.oriDoc", oriDoc); // Intent intent = new Intent(activity, FolderChooserActivity.class); // intent.putExtra(MainFragment.SELECTED_DIR, // new String[] { oriDoc }); // intent.putExtra(MainFragment.SUFFIX, DOC_FILES_SUFFIX); // intent.putExtra(MainFragment.MODE, !MULTI_FILES); // intent.putExtra(MainFragment.CHOOSER_TITLE,MODI_SUFFIX_TITLE); // activity.startActivityForResult(intent, COMPARE_REQUEST_CODE2); // } else { // RESULT_CANCEL // if (selectedFiles.length == 0) { // showToast("Nothing to compare"); // statusView.setText("Nothing to compare"); // } // } // } else if (requestCode == COMPARE_REQUEST_CODE2) { // if (resultCode == Activity.RESULT_OK) { // stopReadAndSearch(); // modifiedDoc = stringExtra[0]; // Log.d("COMPARE_REQUEST_CODE2.modifiedDoc", modifiedDoc); // currentZipFileName = ""; // lm du kh?i show web getSourceFile // selectedFiles = new String[] {oriDoc, modifiedDoc}; // load = "Search"; // requestCompare = true; // requestSearching = false; // getSourceFileTask = new GetSourceFileTask(MainFragment.this); // getSourceFileTask.execute(); // } else { // RESULT_CANCEL // if (selectedFiles.length == 0) { // showToast("Nothing to compare"); // statusView.setText("Nothing to compare"); // } // } } else if (requestCode == GEN_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { Log.d("GEN_REQUEST_CODE.selectedFiles", stringExtra[0]); genStardictTask = new GenStardictTask(MainFragment.this, stringExtra[0]); genStardictTask.execute(); } else { // RESULT_CANCEL if (selectedFiles.length == 0) { showToast("Nothing to generate"); statusView.setText("Nothing to generate"); } } } else if (requestCode == RESTORE_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { Log.d("RESTORE_REQUEST_CODE.selectedFiles", stringExtra[0]); restoreStardictTask = new RestoreStardictTask(MainFragment.this, stringExtra[0]); restoreStardictTask.execute(); } else { // RESULT_CANCEL if (selectedFiles.length == 0) { showToast("Nothing to restore"); statusView.setText("Nothing to restore"); } } } else if (requestCode == DUP_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { stopReadAndSearch(); Log.d("DUP_REQUEST_CODE.selectedFiles", Util.arrayToString(stringExtra, true, MainFragment.LINE_SEP)); if (FileUtils.treeUri == null) {// && !checkFolder(new File(st).getParentFile(), WRITE_REQUEST_CODE)) { FileUtils.applicationContext = activity; FileUtils.treeUri = FileUtils .getSharedPreferenceUri(R.string.key_internal_uri_extsdcard); if (FileUtils.treeUri == null) { AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setTitle("Grant Permission in extSdCard"); alert.setMessage("In the following Android dialog, " + "please select the external SD card and confirm at the bottom."); alert.setCancelable(true); alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { triggerStorageAccessFramework(INTENT_WRITE_REQUEST_CODE); } }); alert.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); } } dupTask = new DupFinderTask(MainFragment.this, stringExtra); dupTask.execute(); } else { // RESULT_CANCEL if (selectedFiles.length == 0) { showToast("Nothing to find"); statusView.setText("Nothing to find"); } } } else if (requestCode == INTENT_WRITE_REQUEST_CODE) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { onActivityResultLollipop(requestCode, resultCode, data); } } else if (requestCode == TRANSLATE_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { Log.d("TRANSLATE_REQUEST_CODE.selectedFiles", stringExtra[0]); stopReadAndSearch(); currentZipFileName = ""; // lm du kh?i show web getSourceFile selectedFiles = stringExtra; load = "Search"; requestCompare = false; requestTranslate = true; requestSearching = false; getSourceFileTask = new GetSourceFileTask(MainFragment.this); getSourceFileTask.execute(); } else { // RESULT_CANCEL if (selectedFiles.length == 0) { showToast("Nothing to translate"); statusView.setText("Nothing to translate"); } } // } else if (requestCode == REPLACE_REQUEST_CODE) { // if (resultCode == Activity.RESULT_OK) { // Log.d("REPLACE_REQUEST_CODE.selectedFiles", stringExtra[0]); // stopReadAndSearch(); // currentZipFileName = ""; // lm du kh?i show web getSourceFile // selectedFiles = stringExtra; // load = "Search"; // requestCompare = false; // requestTranslate = false; // requestSearching = false; // List<File> lf = FileUtil.getFiles(selectedFiles); // if (includeEnter) { // multiline // new ReplaceAllTask(this, lf, isRegex, caseSensitive, new String[]{replace}, new String[]{by}).execute(); // } else { // String[] replaces = replace.split("\r?\n"); // String[] bys = by.split("\r?\n"); // Log.d("bys.length ", bys.length + "."); // if (replaces.length == bys.length) { // new ReplaceAllTask(this, lf, isRegex, caseSensitive, replaces, bys).execute(); // } else { // showToast("The number of lines of replace and by are not equal"); // } // } // getSourceFileTask = new GetSourceFileTask(MainFragment.this); // getSourceFileTask.execute(); // } else { // RESULT_CANCEL // if (selectedFiles.length == 0) { // showToast("Nothing to translate"); // statusView.setText("Nothing to translate"); // } // } // } else if (requestCode == BATCH_REQUEST_CODE_1) { // if (resultCode == Activity.RESULT_OK) { // selectedFiles = stringExtra; // Log.d("BATCH_REQUEST_CODE_1.selectedFiles", Util.arrayToString(selectedFiles, true, "\n")); // Intent intent = new Intent(activity, FolderChooserActivity.class); // intent.putExtra(SearchFragment.SELECTED_DIR, // selectedFiles); // intent.putExtra(SearchFragment.SUFFIX, ""); // intent.putExtra(SearchFragment.MODE, !MULTI_FILES); // intent.putExtra(SearchFragment.CHOOSER_TITLE, "Output Folder"); // activity.startActivityForResult(intent, BATCH_REQUEST_CODE_2); // } else { // RESULT_CANCEL // if (selectedFiles.length == 0) { // showToast("Nothing to convert"); // statusView.setText("Nothing to convert"); // } // } // } else if (requestCode == BATCH_REQUEST_CODE_2) { // if (resultCode == Activity.RESULT_OK) { // stopReadAndSearch(); // outputFolder = stringExtra[0]; // Log.d("BATCH_REQUEST_CODE_2.outputfolder", outputFolder); // currentZipFileName = ""; // lm du kh?i show web getSourceFile // load = "Convert"; // // Log.i(Prefs.TAG, "onCreate ffmpeg4android ProgressBarExample"); //// demoVideoFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/videokit/"; // Log.i(Prefs.TAG, getString(R.string.app_name) + " version: " + GeneralUtils.getVersionName(activity.getApplicationContext()) ); // workFolder = SearchFragment.PRIVATE_PATH + "/"; //activity.getApplicationContext().getFilesDir() + "/"; // Log.i(Prefs.TAG, "workFolder (license and logs location) path: " + workFolder); // vkLogPath = SearchFragment.PRIVATE_PATH + "/vk.log"; // Log.i(Prefs.TAG, "vk log (native log) path: " + vkLogPath); // GeneralUtils.copyLicenseFromAssetsToSDIfNeeded(activity, workFolder); // //GeneralUtils.copyDemoVideoFromAssetsToSDIfNeeded(activity, demoVideoFolder); // int rc = GeneralUtils.isLicenseValid(activity.getApplicationContext(), workFolder); // Log.i(Prefs.TAG, "License check RC: " + rc); // new Thread (new Runnable() { // @Override // public void run() { // List<File> lf = FileUtil.getFiles(selectedFiles); // for (File f : lf) { // Log.i(Prefs.TAG, "f = " + f); // synchronized (command) { // convertingFile = f.getAbsolutePath(); // Log.i(Prefs.TAG, convertingFile + "2=" + convertingFile); // runTranscoding(); // while (!progresssBarFinished) { // try { // Thread.sleep(250); // } catch (InterruptedException e) {} // } // } // } // } // }).start(); // } else { // RESULT_CANCEL // if (selectedFiles.length == 0) { // showToast("Nothing to convert"); // statusView.setText("Nothing to convert"); // } // } } } } catch (Throwable t) { Log.e("onActivityResult", t.getMessage(), t); } Log.d("onActivityResult.load", load + " onActivityResult"); webView.requestFocus(); }
From source file:com.digitalarx.android.files.services.FileUploader.java
/** * Entry point to add one or several files to the queue of uploads. * /* w w w .j ava 2 s . c o m*/ * New uploads are added calling to startService(), resulting in a call to * this method. This ensures the service will keep on working although the * caller activity goes away. */ @Override public int onStartCommand(Intent intent, int flags, int startId) { if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE) || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) { Log_OC.e(TAG, "Not enough information provided in intent"); return Service.START_NOT_STICKY; } int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1); if (uploadType == -1) { Log_OC.e(TAG, "Incorrect upload type provided"); return Service.START_NOT_STICKY; } Account account = intent.getParcelableExtra(KEY_ACCOUNT); String[] localPaths = null, remotePaths = null, mimeTypes = null; OCFile[] files = null; if (uploadType == UPLOAD_SINGLE_FILE) { if (intent.hasExtra(KEY_FILE)) { files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) }; } else { localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) }; remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) }; mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) }; } } else { // mUploadType == UPLOAD_MULTIPLE_FILES if (intent.hasExtra(KEY_FILE)) { files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO // will // this // casting // work // fine? } else { localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE); remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE); mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE); } } FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver()); boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false); boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false); int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY); if (intent.hasExtra(KEY_FILE) && files == null) { Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent"); return Service.START_NOT_STICKY; } else if (!intent.hasExtra(KEY_FILE)) { if (localPaths == null) { Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent"); return Service.START_NOT_STICKY; } if (remotePaths == null) { Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent"); return Service.START_NOT_STICKY; } if (localPaths.length != remotePaths.length) { Log_OC.e(TAG, "Different number of remote paths and local paths!"); return Service.START_NOT_STICKY; } files = new OCFile[localPaths.length]; for (int i = 0; i < localPaths.length; i++) { files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes != null) ? mimeTypes[i] : (String) null), storageManager); if (files[i] == null) { // TODO @andomaex add failure Notification return Service.START_NOT_STICKY; } } } AccountManager aMgr = AccountManager.get(this); String version = aMgr.getUserData(account, Constants.KEY_OC_VERSION); OwnCloudVersion ocv = new OwnCloudVersion(version); boolean chunked = FileUploader.chunkedUploadIsSupported(ocv); AbstractList<String> requestedUploads = new Vector<String>(); String uploadKey = null; UploadFileOperation newUpload = null; try { for (int i = 0; i < files.length; i++) { uploadKey = buildRemoteName(account, files[i].getRemotePath()); newUpload = new UploadFileOperation(account, files[i], chunked, isInstant, forceOverwrite, localAction, getApplicationContext()); if (isInstant) { newUpload.setRemoteFolderToBeCreated(); } mPendingUploads.putIfAbsent(uploadKey, newUpload); // Grants that the file only upload once time newUpload.addDatatransferProgressListener(this); newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder); requestedUploads.add(uploadKey); } } catch (IllegalArgumentException e) { Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage()); return START_NOT_STICKY; } catch (IllegalStateException e) { Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage()); return START_NOT_STICKY; } catch (Exception e) { Log_OC.e(TAG, "Unexpected exception while processing upload intent", e); return START_NOT_STICKY; } if (requestedUploads.size() > 0) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = requestedUploads; mServiceHandler.sendMessage(msg); } Log_OC.i(TAG, "mPendingUploads size:" + mPendingUploads.size()); return Service.START_NOT_STICKY; }
From source file:com.tasomaniac.openwith.resolver.ResolverActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { final Intent intent = makeMyIntent(); setTheme(R.style.BottomSheet_Light); super.onCreate(savedInstanceState); mPm = getPackageManager();/*from ww w .j a va 2 s . c om*/ mRequestedUri = intent.getData(); boolean isCallerPackagePreferred = false; final String callerPackage = getCallerPackage(); ResolveInfo lastChosen = null; final Cursor query = getContentResolver().query(withHost(intent.getData().getHost()), null, null, null, null); if (query != null && query.moveToFirst()) { final boolean isPreferred = query.getInt(query.getColumnIndex(PREFERRED)) == 1; final boolean isLastChosen = query.getInt(query.getColumnIndex(LAST_CHOSEN)) == 1; if (isPreferred || isLastChosen) { final String componentString = query.getString(query.getColumnIndex(COMPONENT)); final Intent lastChosenIntent = new Intent(); final ComponentName lastChosenComponent = ComponentName.unflattenFromString(componentString); lastChosenIntent.setComponent(lastChosenComponent); ResolveInfo ri = mPm.resolveActivity(lastChosenIntent, PackageManager.MATCH_DEFAULT_ONLY); if (isPreferred && ri != null) { isCallerPackagePreferred = ri.activityInfo.packageName.equals(callerPackage); if (!isCallerPackagePreferred) { intent.setComponent(lastChosenComponent); startActivity(intent); finish(); return; } } lastChosen = ri; } query.close(); } mPackageMonitor.register(this, getMainLooper(), false); mRegistered = true; final ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); mIconDpi = am.getLauncherLargeIconDensity(); mAdapter = new ResolveListAdapter(this, getHistory(), intent, callerPackage, lastChosen, true); mAdapter.setPriorityItems(intent.getStringArrayExtra(EXTRA_PRIORITY_PACKAGES)); mAlwaysUseOption = true; final int layoutId; final boolean useHeader; if (mAdapter.hasFilteredItem()) { layoutId = R.layout.resolver_list_with_default; mAlwaysUseOption = false; useHeader = true; } else { useHeader = false; layoutId = R.layout.resolver_list; } //If the caller is already the preferred, don't change it. if (isCallerPackagePreferred) { mAlwaysUseOption = false; } int count = mAdapter.mList.size(); if (count > 1) { setContentView(layoutId); mListView = (RecyclerView) findViewById(R.id.resolver_list); mListView.setAdapter(mAdapter); mAdapter.setOnItemClickedListener(this); mAdapter.setOnItemLongClickedListener(this); if (mAlwaysUseOption) { mAdapter.setSelectable(true); } if (useHeader) { mAdapter.setHeader(new ResolveListAdapter.Header()); } } else if (count == 1) { startActivity(mAdapter.intentForPosition(0, false)); mPackageMonitor.unregister(); mRegistered = false; finish(); return; } else { setContentView(R.layout.resolver_list); final TextView empty = (TextView) findViewById(R.id.empty); empty.setVisibility(View.VISIBLE); mListView = (RecyclerView) findViewById(R.id.resolver_list); mListView.setVisibility(View.GONE); } mListView.setLayoutManager(new LinearLayoutManager(this)); // Prevent the Resolver window from becoming the top fullscreen window and thus from taking // control of the system bars. getWindow().clearFlags(FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR); final ResolverDrawerLayout rdl = (ResolverDrawerLayout) findViewById(R.id.contentPanel); if (rdl != null) { rdl.setOnDismissedListener(new ResolverDrawerLayout.OnDismissedListener() { @Override public void onDismissed() { finish(); } }); } CharSequence title = getTitleForAction(); if (!TextUtils.isEmpty(title)) { final TextView titleView = (TextView) findViewById(R.id.title); if (titleView != null) { titleView.setText(title); } setTitle(title); } final ImageView iconView = (ImageView) findViewById(R.id.icon); final DisplayResolveInfo iconInfo = mAdapter.getFilteredItem(); if (iconView != null && iconInfo != null) { new LoadIconIntoViewTask(iconView).execute(iconInfo); } if (mAlwaysUseOption || mAdapter.hasFilteredItem()) { final ViewGroup buttonLayout = (ViewGroup) findViewById(R.id.button_bar); if (buttonLayout != null) { buttonLayout.setVisibility(View.VISIBLE); mAlwaysButton = (Button) buttonLayout.findViewById(R.id.button_always); mOnceButton = (Button) buttonLayout.findViewById(R.id.button_once); } else { mAlwaysUseOption = false; } } if (mAdapter.hasFilteredItem()) { mAlwaysButton.setEnabled(true); mOnceButton.setEnabled(true); } }
From source file:com.keylesspalace.tusky.ComposeActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String theme = preferences.getString("appTheme", ThemeUtils.APP_THEME_DEFAULT); if (theme.equals("black")) { setTheme(R.style.TuskyDialogActivityBlackTheme); }//from w ww . j a v a2 s . com setContentView(R.layout.activity_compose); replyTextView = findViewById(R.id.composeReplyView); replyContentTextView = findViewById(R.id.composeReplyContentView); textEditor = findViewById(R.id.composeEditField); mediaPreviewBar = findViewById(R.id.compose_media_preview_bar); contentWarningBar = findViewById(R.id.composeContentWarningBar); contentWarningEditor = findViewById(R.id.composeContentWarningField); charactersLeft = findViewById(R.id.composeCharactersLeftView); tootButton = findViewById(R.id.composeTootButton); pickButton = findViewById(R.id.composeAddMediaButton); visibilityButton = findViewById(R.id.composeToggleVisibilityButton); contentWarningButton = findViewById(R.id.composeContentWarningButton); emojiButton = findViewById(R.id.composeEmojiButton); hideMediaToggle = findViewById(R.id.composeHideMediaButton); emojiView = findViewById(R.id.emojiView); emojiList = Collections.emptyList(); saveTootHelper = new SaveTootHelper(database.tootDao(), this); // Setup the toolbar. Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(null); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp); ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint); actionBar.setHomeAsUpIndicator(closeIcon); } // setup the account image final AccountEntity activeAccount = accountManager.getActiveAccount(); if (activeAccount != null) { ImageView composeAvatar = findViewById(R.id.composeAvatar); if (TextUtils.isEmpty(activeAccount.getProfilePictureUrl())) { composeAvatar.setImageResource(R.drawable.avatar_default); } else { Picasso.with(this).load(activeAccount.getProfilePictureUrl()).error(R.drawable.avatar_default) .placeholder(R.drawable.avatar_default).into(composeAvatar); } composeAvatar.setContentDescription( getString(R.string.compose_active_account_description, activeAccount.getFullName())); mastodonApi.getInstance().enqueue(new Callback<Instance>() { @Override public void onResponse(@NonNull Call<Instance> call, @NonNull Response<Instance> response) { if (response.isSuccessful() && response.body().getMaxTootChars() != null) { maximumTootCharacters = response.body().getMaxTootChars(); updateVisibleCharactersLeft(); cacheInstanceMetadata(activeAccount); } } @Override public void onFailure(@NonNull Call<Instance> call, @NonNull Throwable t) { Log.w(TAG, "error loading instance data", t); loadCachedInstanceMetadata(activeAccount); } }); mastodonApi.getCustomEmojis().enqueue(new Callback<List<Emoji>>() { @Override public void onResponse(@NonNull Call<List<Emoji>> call, @NonNull Response<List<Emoji>> response) { emojiList = response.body(); setEmojiList(emojiList); cacheInstanceMetadata(activeAccount); } @Override public void onFailure(@NonNull Call<List<Emoji>> call, @NonNull Throwable t) { Log.w(TAG, "error loading custom emojis", t); loadCachedInstanceMetadata(activeAccount); } }); } else { // do not do anything when not logged in, activity will be finished in super.onCreate() anyway return; } composeOptionsView = findViewById(R.id.composeOptionsBottomSheet); composeOptionsView.setListener(this); composeOptionsBehavior = BottomSheetBehavior.from(composeOptionsView); composeOptionsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); addMediaBehavior = BottomSheetBehavior.from(findViewById(R.id.addMediaBottomSheet)); emojiBehavior = BottomSheetBehavior.from(emojiView); emojiView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.HORIZONTAL, false)); enableButton(emojiButton, false, false); // Setup the interface buttons. tootButton.setOnClickListener(v -> onSendClicked()); pickButton.setOnClickListener(v -> openPickDialog()); visibilityButton.setOnClickListener(v -> showComposeOptions()); contentWarningButton.setOnClickListener(v -> onContentWarningChanged()); emojiButton.setOnClickListener(v -> showEmojis()); hideMediaToggle.setOnClickListener(v -> toggleHideMedia()); TextView actionPhotoTake = findViewById(R.id.action_photo_take); TextView actionPhotoPick = findViewById(R.id.action_photo_pick); int textColor = ThemeUtils.getColor(this, android.R.attr.textColorTertiary); Drawable cameraIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_alt).color(textColor) .sizeDp(18); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoTake, cameraIcon, null, null, null); Drawable imageIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_image).color(textColor).sizeDp(18); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoPick, imageIcon, null, null, null); actionPhotoTake.setOnClickListener(v -> initiateCameraApp()); actionPhotoPick.setOnClickListener(v -> onMediaPick()); thumbnailViewSize = getResources().getDimensionPixelSize(R.dimen.compose_media_preview_size); /* Initialise all the state, or restore it from a previous run, to determine a "starting" * state. */ Status.Visibility startingVisibility = Status.Visibility.UNKNOWN; boolean startingHideText; ArrayList<SavedQueuedMedia> savedMediaQueued = null; if (savedInstanceState != null) { startingVisibility = Status.Visibility .byNum(savedInstanceState.getInt("statusVisibility", Status.Visibility.PUBLIC.getNum())); statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive"); startingHideText = savedInstanceState.getBoolean("statusHideText"); // Keep these until everything needed to put them in the queue is finished initializing. savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued"); // These are for restoring an in-progress commit content operation. InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo")); int previousFlags = savedInstanceState.getInt("commitContentFlags"); if (previousInputContentInfo != null) { onCommitContentInternal(previousInputContentInfo, previousFlags); } photoUploadUri = savedInstanceState.getParcelable("photoUploadUri"); } else { statusMarkSensitive = false; startingHideText = false; photoUploadUri = null; } /* If the composer is started up as a reply to another post, override the "starting" state * based on what the intent from the reply request passes. */ Intent intent = getIntent(); String[] mentionedUsernames = null; ArrayList<String> loadedDraftMediaUris = null; inReplyToId = null; if (intent != null) { if (startingVisibility == Status.Visibility.UNKNOWN) { Status.Visibility preferredVisibility = Status.Visibility.byString( preferences.getString("defaultPostPrivacy", Status.Visibility.PUBLIC.serverString())); Status.Visibility replyVisibility = Status.Visibility .byNum(intent.getIntExtra(REPLY_VISIBILITY_EXTRA, Status.Visibility.UNKNOWN.getNum())); startingVisibility = Status.Visibility .byNum(Math.max(preferredVisibility.getNum(), replyVisibility.getNum())); } inReplyToId = intent.getStringExtra(IN_REPLY_TO_ID_EXTRA); mentionedUsernames = intent.getStringArrayExtra(MENTIONED_USERNAMES_EXTRA); String contentWarning = intent.getStringExtra(CONTENT_WARNING_EXTRA); if (contentWarning != null) { startingHideText = !contentWarning.isEmpty(); if (startingHideText) { startingContentWarning = contentWarning; } } // If come from SavedTootActivity String savedTootText = intent.getStringExtra(SAVED_TOOT_TEXT_EXTRA); if (!TextUtils.isEmpty(savedTootText)) { startingText = savedTootText; textEditor.setText(savedTootText); } String savedJsonUrls = intent.getStringExtra(SAVED_JSON_URLS_EXTRA); if (!TextUtils.isEmpty(savedJsonUrls)) { // try to redo a list of media loadedDraftMediaUris = new Gson().fromJson(savedJsonUrls, new TypeToken<ArrayList<String>>() { }.getType()); } int savedTootUid = intent.getIntExtra(SAVED_TOOT_UID_EXTRA, 0); if (savedTootUid != 0) { this.savedTootUid = savedTootUid; } if (intent.hasExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA)) { replyTextView.setVisibility(View.VISIBLE); String username = intent.getStringExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA); replyTextView.setText(getString(R.string.replying_to, username)); Drawable arrowDownIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_down) .sizeDp(12); ThemeUtils.setDrawableTint(this, arrowDownIcon, android.R.attr.textColorTertiary); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowDownIcon, null); replyTextView.setOnClickListener(v -> { TransitionManager.beginDelayedTransition((ViewGroup) replyContentTextView.getParent()); if (replyContentTextView.getVisibility() != View.VISIBLE) { replyContentTextView.setVisibility(View.VISIBLE); Drawable arrowUpIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_up) .sizeDp(12); ThemeUtils.setDrawableTint(this, arrowUpIcon, android.R.attr.textColorTertiary); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowUpIcon, null); } else { replyContentTextView.setVisibility(View.GONE); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowDownIcon, null); } }); } if (intent.hasExtra(REPLYING_STATUS_CONTENT_EXTRA)) { replyContentTextView.setText(intent.getStringExtra(REPLYING_STATUS_CONTENT_EXTRA)); } } // After the starting state is finalised, the interface can be set to reflect this state. setStatusVisibility(startingVisibility); updateHideMediaToggle(); updateVisibleCharactersLeft(); // Setup the main text field. textEditor.setOnCommitContentListener(this); final int mentionColour = textEditor.getLinkTextColors().getDefaultColor(); SpanUtilsKt.highlightSpans(textEditor.getText(), mentionColour); textEditor.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable editable) { SpanUtilsKt.highlightSpans(editable, mentionColour); updateVisibleCharactersLeft(); } }); textEditor.setAdapter(new MentionAutoCompleteAdapter(this, R.layout.item_autocomplete, this)); textEditor.setTokenizer(new MentionTokenizer()); // Add any mentions to the text field when a reply is first composed. if (mentionedUsernames != null) { StringBuilder builder = new StringBuilder(); for (String name : mentionedUsernames) { builder.append('@'); builder.append(name); builder.append(' '); } startingText = builder.toString(); textEditor.setText(startingText); textEditor.setSelection(textEditor.length()); } // work around Android platform bug -> https://issuetracker.google.com/issues/67102093 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) { textEditor.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } // Initialise the content warning editor. contentWarningEditor.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { updateVisibleCharactersLeft(); } @Override public void afterTextChanged(Editable s) { } }); showContentWarning(startingHideText); if (startingContentWarning != null) { contentWarningEditor.setText(startingContentWarning); } // Initialise the empty media queue state. waitForMediaLatch = new CountUpDownLatch(); // These can only be added after everything affected by the media queue is initialized. if (!ListUtils.isEmpty(loadedDraftMediaUris)) { for (String uriString : loadedDraftMediaUris) { Uri uri = Uri.parse(uriString); long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri); pickMedia(uri, mediaSize); } } else if (savedMediaQueued != null) { for (SavedQueuedMedia item : savedMediaQueued) { Bitmap preview = MediaUtils.getImageThumbnail(getContentResolver(), item.uri, thumbnailViewSize); addMediaToQueue(item.id, item.type, preview, item.uri, item.mediaSize, item.readyStage, item.description); } } else if (intent != null && savedInstanceState == null) { /* Get incoming images being sent through a share action from another app. Only do this * when savedInstanceState is null, otherwise both the images from the intent and the * instance state will be re-queued. */ String type = intent.getType(); if (type != null) { if (type.startsWith("image/")) { List<Uri> uriList = new ArrayList<>(); if (intent.getAction() != null) { switch (intent.getAction()) { case Intent.ACTION_SEND: { Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (uri != null) { uriList.add(uri); } break; } case Intent.ACTION_SEND_MULTIPLE: { ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Uri uri : list) { if (uri != null) { uriList.add(uri); } } } break; } } } for (Uri uri : uriList) { long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri); pickMedia(uri, mediaSize); } } else if (type.equals("text/plain")) { String action = intent.getAction(); if (action != null && action.equals(Intent.ACTION_SEND)) { String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (text != null) { int start = Math.max(textEditor.getSelectionStart(), 0); int end = Math.max(textEditor.getSelectionEnd(), 0); int left = Math.min(start, end); int right = Math.max(start, end); textEditor.getText().replace(left, right, text, 0, text.length()); } } } } } textEditor.requestFocus(); }
From source file:com.fenlisproject.elf.core.framework.ElfBinder.java
public static void bindIntentExtra(Object receiver) { Field[] fields = receiver.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true);/*from ww w . j av a 2 s.c o m*/ IntentExtra intentExtra = field.getAnnotation(IntentExtra.class); if (intentExtra != null) { try { Intent intent = null; if (receiver instanceof Activity) { intent = ((Activity) receiver).getIntent(); } else if (receiver instanceof Fragment) { intent = ((Fragment) receiver).getActivity().getIntent(); } if (intent != null) { Class<?> type = field.getType(); if (type == Boolean.class || type == boolean.class) { field.set(receiver, intent.getBooleanExtra(intentExtra.value(), false)); } else if (type == Byte.class || type == byte.class) { field.set(receiver, intent.getByteExtra(intentExtra.value(), (byte) 0)); } else if (type == Character.class || type == char.class) { field.set(receiver, intent.getCharExtra(intentExtra.value(), '\u0000')); } else if (type == Double.class || type == double.class) { field.set(receiver, intent.getDoubleExtra(intentExtra.value(), 0.0d)); } else if (type == Float.class || type == float.class) { field.set(receiver, intent.getFloatExtra(intentExtra.value(), 0.0f)); } else if (type == Integer.class || type == int.class) { field.set(receiver, intent.getIntExtra(intentExtra.value(), 0)); } else if (type == Long.class || type == long.class) { field.set(receiver, intent.getLongExtra(intentExtra.value(), 0L)); } else if (type == Short.class || type == short.class) { field.set(receiver, intent.getShortExtra(intentExtra.value(), (short) 0)); } else if (type == String.class) { field.set(receiver, intent.getStringExtra(intentExtra.value())); } else if (type == Boolean[].class || type == boolean[].class) { field.set(receiver, intent.getBooleanArrayExtra(intentExtra.value())); } else if (type == Byte[].class || type == byte[].class) { field.set(receiver, intent.getByteArrayExtra(intentExtra.value())); } else if (type == Character[].class || type == char[].class) { field.set(receiver, intent.getCharArrayExtra(intentExtra.value())); } else if (type == Double[].class || type == double[].class) { field.set(receiver, intent.getDoubleArrayExtra(intentExtra.value())); } else if (type == Float[].class || type == float[].class) { field.set(receiver, intent.getFloatArrayExtra(intentExtra.value())); } else if (type == Integer[].class || type == int[].class) { field.set(receiver, intent.getIntArrayExtra(intentExtra.value())); } else if (type == Long[].class || type == long[].class) { field.set(receiver, intent.getLongArrayExtra(intentExtra.value())); } else if (type == Short[].class || type == short[].class) { field.set(receiver, intent.getShortArrayExtra(intentExtra.value())); } else if (type == String[].class) { field.set(receiver, intent.getStringArrayExtra(intentExtra.value())); } else if (Serializable.class.isAssignableFrom(type)) { field.set(receiver, intent.getSerializableExtra(intentExtra.value())); } else if (type == Bundle.class) { field.set(receiver, intent.getBundleExtra(intentExtra.value())); } } } catch (IllegalAccessException e) { e.printStackTrace(); } } } }
From source file:com.owncloud.android.files.services.FileUploader.java
/** * Entry point to add one or several files to the queue of uploads. * * New uploads are added calling to startService(), resulting in a call to * this method. This ensures the service will keep on working although the * caller activity goes away.// w ww .j a va 2 s . c o m */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Log_OC.d(TAG, "Starting command with id " + startId); if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE) || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) { Log_OC.e(TAG, "Not enough information provided in intent"); return Service.START_NOT_STICKY; } int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1); if (uploadType == -1) { Log_OC.e(TAG, "Incorrect upload type provided"); return Service.START_NOT_STICKY; } Account account = intent.getParcelableExtra(KEY_ACCOUNT); if (!AccountUtils.exists(account, getApplicationContext())) { return Service.START_NOT_STICKY; } String[] localPaths = null, remotePaths = null, mimeTypes = null; OCFile[] files = null; if (uploadType == UPLOAD_SINGLE_FILE) { if (intent.hasExtra(KEY_FILE)) { files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) }; } else { localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) }; remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) }; mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) }; } } else { // mUploadType == UPLOAD_MULTIPLE_FILES if (intent.hasExtra(KEY_FILE)) { files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO // will // this // casting // work // fine? } else { localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE); remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE); mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE); } } FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver()); boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false); boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false); int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY); if (intent.hasExtra(KEY_FILE) && files == null) { Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent"); return Service.START_NOT_STICKY; } else if (!intent.hasExtra(KEY_FILE)) { if (localPaths == null) { Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent"); return Service.START_NOT_STICKY; } if (remotePaths == null) { Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent"); return Service.START_NOT_STICKY; } if (localPaths.length != remotePaths.length) { Log_OC.e(TAG, "Different number of remote paths and local paths!"); return Service.START_NOT_STICKY; } files = new OCFile[localPaths.length]; for (int i = 0; i < localPaths.length; i++) { files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes != null) ? mimeTypes[i] : null)); if (files[i] == null) { // TODO @andomaex add failure Notification return Service.START_NOT_STICKY; } } } OwnCloudVersion ocv = AccountUtils.getServerVersion(account); boolean chunked = FileUploader.chunkedUploadIsSupported(ocv); AbstractList<String> requestedUploads = new Vector<String>(); String uploadKey = null; UploadFileOperation newUpload = null; try { for (int i = 0; i < files.length; i++) { newUpload = new UploadFileOperation(account, files[i], chunked, isInstant, forceOverwrite, localAction, getApplicationContext()); if (isInstant) { newUpload.setRemoteFolderToBeCreated(); } newUpload.addDatatransferProgressListener(this); newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder); Pair<String, String> putResult = mPendingUploads.putIfAbsent(account, files[i].getRemotePath(), newUpload); uploadKey = putResult.first; requestedUploads.add(uploadKey); } } catch (IllegalArgumentException e) { Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage()); return START_NOT_STICKY; } catch (IllegalStateException e) { Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage()); return START_NOT_STICKY; } catch (Exception e) { Log_OC.e(TAG, "Unexpected exception while processing upload intent", e); return START_NOT_STICKY; } if (requestedUploads.size() > 0) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = requestedUploads; mServiceHandler.sendMessage(msg); } return Service.START_NOT_STICKY; }
From source file:com.synox.android.files.services.FileUploader.java
/** * Entry point to add one or several files to the queue of uploads. * * New uploads are added calling to startService(), resulting in a call to * this method. This ensures the service will keep on working although the * caller activity goes away./*from www.ja va2s.co m*/ */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Log_OC.d(TAG, "Starting command with id " + startId); if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE) || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) { Log_OC.e(TAG, "Not enough information provided in intent"); return Service.START_NOT_STICKY; } int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1); if (uploadType == -1) { Log_OC.e(TAG, "Incorrect upload type provided"); return Service.START_NOT_STICKY; } Account account = intent.getParcelableExtra(KEY_ACCOUNT); if (!AccountUtils.exists(account, getApplicationContext())) { return Service.START_NOT_STICKY; } String[] localPaths = null, remotePaths = null, mimeTypes = null; OCFile[] files = null; if (uploadType == UPLOAD_SINGLE_FILE) { if (intent.hasExtra(KEY_FILE)) { files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) }; } else { localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) }; remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) }; mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) }; } } else { // mUploadType == UPLOAD_MULTIPLE_FILES if (intent.hasExtra(KEY_FILE)) { files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO // will // this // casting // work // fine? } else { localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE); remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE); mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE); } } FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver()); boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false); boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false); int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY); if (intent.hasExtra(KEY_FILE) && files == null) { Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent"); return Service.START_NOT_STICKY; } else if (!intent.hasExtra(KEY_FILE)) { if (localPaths == null) { Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent"); return Service.START_NOT_STICKY; } if (remotePaths == null) { Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent"); return Service.START_NOT_STICKY; } if (localPaths.length != remotePaths.length) { Log_OC.e(TAG, "Different number of remote paths and local paths!"); return Service.START_NOT_STICKY; } files = new OCFile[localPaths.length]; for (int i = 0; i < localPaths.length; i++) { files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes != null) ? mimeTypes[i] : null), storageManager); if (files[i] == null) { // TODO @andomaex add failure Notification return Service.START_NOT_STICKY; } } } OwnCloudVersion ocv = AccountUtils.getServerVersion(account); boolean chunked = FileUploader.chunkedUploadIsSupported(ocv); AbstractList<String> requestedUploads = new Vector<>(); String uploadKey = null; UploadFileOperation newUpload = null; try { for (OCFile file : files) { uploadKey = buildRemoteName(account, file.getRemotePath()); newUpload = new UploadFileOperation(account, file, chunked, isInstant, forceOverwrite, localAction, getApplicationContext()); if (isInstant) { newUpload.setRemoteFolderToBeCreated(); } // Grants that the file only upload once time mPendingUploads.putIfAbsent(uploadKey, newUpload); newUpload.addDatatransferProgressListener(this); newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder); requestedUploads.add(uploadKey); } } catch (IllegalArgumentException e) { Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage()); return START_NOT_STICKY; } catch (IllegalStateException e) { Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage()); return START_NOT_STICKY; } catch (Exception e) { Log_OC.e(TAG, "Unexpected exception while processing upload intent", e); return START_NOT_STICKY; } if (requestedUploads.size() > 0) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = requestedUploads; mServiceHandler.sendMessage(msg); } Log_OC.i(TAG, "mPendingUploads size:" + mPendingUploads.size()); return Service.START_NOT_STICKY; }
From source file:org.transdroid.gui.TorrentsFragment.java
public void handleIntent(final Intent startIntent) { // Handle new intents that come from either a regular application startup, a startup from a // new intent or a new intent being send with the application already started if (startIntent != null && (startIntent.getData() != null || (startIntent.getAction() != null && startIntent.getAction().equals(Transdroid.INTENT_ADD_MULTIPLE))) && !isLaunchedFromHistory(startIntent)) { if (startIntent.getAction() != null && startIntent.getAction().equals(Transdroid.INTENT_ADD_MULTIPLE)) { // Intent should have some extras pointing to possibly multiple torrents String[] urls = startIntent.getStringArrayExtra(Transdroid.INTENT_TORRENT_URLS); String[] titles = startIntent.getStringArrayExtra(Transdroid.INTENT_TORRENT_TITLES); if (urls != null) { for (int i = 0; i < urls.length; i++) { addTorrentByUrl(urls[i], (titles != null && titles.length >= i ? titles[i] : "Torrent")); }// w ww . j a v a 2s. co m } } else { // Intent should have some Uri data pointing to a single torrent String data = startIntent.getDataString(); if (data != null && startIntent.getData() != null && startIntent.getData().getScheme() != null) { // From Android 4.2 the file path is not directly in the Intent :( but rather in the 'Download manager' cursor if (startIntent.getData().getScheme().equals(ContentResolver.SCHEME_CONTENT)) { addTorrentFromDownloads(startIntent.getData()); } else if (startIntent.getData().getScheme().equals(HttpHelper.SCHEME_HTTP) || startIntent.getData().getScheme().equals(HttpHelper.SCHEME_HTTPS)) { // From a global intent to add a .torrent file via URL (maybe form the browser) String title = data.substring(data.lastIndexOf("/")); if (startIntent.hasExtra(Transdroid.INTENT_TORRENT_TITLE)) { title = startIntent.getStringExtra(Transdroid.INTENT_TORRENT_TITLE); } addTorrentByUrl(data, title); } else if (startIntent.getData().getScheme().equals(HttpHelper.SCHEME_MAGNET)) { // From a global intent to add a magnet link via URL (usually from the browser) addTorrentByMagnetUrl(data); } else if (startIntent.getData().getScheme().equals(HttpHelper.SCHEME_FILE)) { // From a global intent to add via the contents of a local .torrent file (maybe form a file manager) addTorrentByFile(data); } } } } // Possibly switch to a specific daemon (other than the last used) boolean forceUpdate = false; if (startIntent != null && !isLaunchedFromHistory(startIntent) && startIntent.hasExtra(Transdroid.INTENT_OPENDAEMON)) { String openDaemon = startIntent.getStringExtra(Transdroid.INTENT_OPENDAEMON); if (!daemon.getSettings().getIdString().equals(openDaemon)) { int openDaemonI = (openDaemon == null || openDaemon.equals("") ? 0 : Integer.parseInt(openDaemon)); if (openDaemonI >= allDaemonSettings.size()) { openDaemonI = 0; } forceUpdate = true; switchDaemonConfig(openDaemonI); } } if (forceUpdate || allTorrents == null) { // Not swithcing to another daemon and no known list of torrents: update updateTorrentList(); } else { // We retained the list of torrents form the fragment state: show again updateStatusText(null); updateTorrentsView(false); } }