Java Code Examples for android.net.Uri#toString()

The following examples show how to use android.net.Uri#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageSource.java    From PdfViewPager with Apache License 2.0 6 votes vote down vote up
private ImageSource(@NonNull Uri uri) {
    // #114 If file doesn't exist, attempt to url decode the URI and try again
    String uriString = uri.toString();
    if (uriString.startsWith(FILE_SCHEME)) {
        File uriFile = new File(uriString.substring(FILE_SCHEME.length() - 1));
        if (!uriFile.exists()) {
            try {
                uri = Uri.parse(URLDecoder.decode(uriString, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // Fallback to encoded URI. This exception is not expected.
            }
        }
    }
    this.bitmap = null;
    this.uri = uri;
    this.resource = null;
    this.tile = true;
}
 
Example 2
Source File: DocumentUtils.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Finishes tasks other than the one with the given ID that were started with the given data
 * in the Intent, removing those tasks from Recents and leaving a unique task with the data.
 * @param data Passed in as part of the Intent's data when starting the Activity.
 * @param canonicalTaskId ID of the task will be the only one left with the ID.
 * @return Intent of one of the tasks that were finished.
 */
public static Intent finishOtherTasksWithData(Uri data, int canonicalTaskId) {
    if (data == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null;

    String dataString = data.toString();
    Context context = ContextUtils.getApplicationContext();

    ActivityManager manager =
            (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.AppTask> tasksToFinish = new ArrayList<ActivityManager.AppTask>();
    for (ActivityManager.AppTask task : manager.getAppTasks()) {
        RecentTaskInfo taskInfo = getTaskInfoFromTask(task);
        if (taskInfo == null) continue;
        int taskId = taskInfo.id;

        Intent baseIntent = taskInfo.baseIntent;
        String taskData = baseIntent == null ? null : taskInfo.baseIntent.getDataString();

        if (TextUtils.equals(dataString, taskData)
                && (taskId == -1 || taskId != canonicalTaskId)) {
            tasksToFinish.add(task);
        }
    }
    return finishAndRemoveTasks(tasksToFinish);
}
 
Example 3
Source File: ImageSource.java    From PictureSelector with Apache License 2.0 6 votes vote down vote up
private ImageSource(Uri uri) {
    // #114 If file doesn't exist, attempt to url decode the URI and try again
    String uriString = uri.toString();
    if (uriString.startsWith(FILE_SCHEME)) {
        File uriFile = new File(uriString.substring(FILE_SCHEME.length() - 1));
        if (!uriFile.exists()) {
            try {
                uri = Uri.parse(URLDecoder.decode(uriString, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // Fallback to encoded URI. This exception is not expected.
            }
        }
    }
    this.bitmap = null;
    this.uri = uri;
    this.resource = null;
    this.tile = true;
}
 
Example 4
Source File: CallbackHelper.java    From Auth0.Android with MIT License 6 votes vote down vote up
/**
 * Generates the callback Uri for the given domain.
 *
 * @return the callback Uri.
 */
static String getCallbackUri(@NonNull String scheme, @NonNull String packageName, @NonNull String domain) {
    if (!URLUtil.isValidUrl(domain)) {
        Log.e(TAG, "The Domain is invalid and the Callback URI will not be set. You used: " + domain);
        return null;
    }

    Uri uri = Uri.parse(domain)
            .buildUpon()
            .scheme(scheme)
            .appendPath("android")
            .appendPath(packageName)
            .appendPath("callback")
            .build();

    Log.v(TAG, "The Callback URI is: " + uri);
    return uri.toString();
}
 
Example 5
Source File: QueueRecordProvider.java    From bitseal with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Takes an QueueRecord object and adds it to the app's 
   * SQLite database as a new record, returning the ID of the 
   * newly created record. 
   * 
   * @param q - The QueueRecord object to be added
   * 
   * @return id - A long value representing the ID of the newly
   * created record
   */
  public long addQueueRecord(QueueRecord q)
  {	
  	ContentValues values = new ContentValues();
  	values.put(QueueRecordsTable.COLUMN_TASK, q.getTask());
  	values.put(QueueRecordsTable.COLUMN_TRIGGER_TIME, q.getTriggerTime());
  	values.put(QueueRecordsTable.COLUMN_RECORD_COUNT, q.getRecordCount());
  	values.put(QueueRecordsTable.COLUMN_LAST_ATTEMPT_TIME, q.getLastAttemptTime());
  	values.put(QueueRecordsTable.COLUMN_ATTEMPTS, q.getAttempts());
  	values.put(QueueRecordsTable.COLUMN_OBJECT_0_ID, q.getObject0Id());
  	values.put(QueueRecordsTable.COLUMN_OBJECT_0_TYPE, q.getObject0Type());
  	values.put(QueueRecordsTable.COLUMN_OBJECT_1_ID, q.getObject1Id());
  	values.put(QueueRecordsTable.COLUMN_OBJECT_1_TYPE, q.getObject1Type());
  	values.put(QueueRecordsTable.COLUMN_OBJECT_2_ID, q.getObject2Id());
  	values.put(QueueRecordsTable.COLUMN_OBJECT_2_TYPE, q.getObject2Type());
	
Uri insertionUri = mContentResolver.insert(DatabaseContentProvider.CONTENT_URI_QUEUE_RECORDS, values);	
  	Log.i(TAG, "QueueRecord with task " + q.getTask() + " and number of attempts " + q.getAttempts() + " saved to database");
  	
// Parse the ID of the newly created record from the insertion URI
String uriString = insertionUri.toString();
String idString = uriString.substring(uriString.indexOf("/") + 1);
long id = Long.parseLong(idString);
return id;
  }
 
Example 6
Source File: RiotGameUtils.java    From Theogony with MIT License 6 votes vote down vote up
/**
 * 创建技能视频URL
 *
 * @param championId
 * @param spellIndex 技能顺序从零开始
 * @return
 */
public static String createSpellVideoUrl(int championId, int spellIndex) {
    if (championId <= 0) {
        throw new IllegalArgumentException("championId出错," + championId);
    }
    if (spellIndex < 0 || spellIndex > 4) {
        throw new IllegalArgumentException("spellIndex出错," + spellIndex);
    }
    final String baseSpellVideoUrl = "https://lolstatic-a.akamaihd.net/champion-abilities/videos/mp4";
    final String spellVideoName = String.format("%04d_%02d.mp4", championId, spellIndex); //0024_01.mp4
    Uri uri = Uri.parse(baseSpellVideoUrl)
            .buildUpon()
            .appendPath(spellVideoName)
            .build();
    return uri.toString();
}
 
Example 7
Source File: NetworkUtils.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
/**
 * Builds the URL used to talk to the weather server using latitude and longitude of a
 * location.
 *
 * @param latitude  The latitude of the location
 * @param longitude The longitude of the location
 * @return The Url to use to query the weather server.
 */
private static URL buildUrlWithLatitudeLongitude(Double latitude, Double longitude) {
    Uri weatherQueryUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
            .appendQueryParameter(LAT_PARAM, String.valueOf(latitude))
            .appendQueryParameter(LON_PARAM, String.valueOf(longitude))
            .appendQueryParameter(FORMAT_PARAM, format)
            .appendQueryParameter(UNITS_PARAM, units)
            .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
            .build();

    try {
        URL weatherQueryUrl = new URL(weatherQueryUri.toString());
        Log.v(TAG, "URL: " + weatherQueryUrl);
        return weatherQueryUrl;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 8
Source File: UriTypeAdapter.java    From StoreBox with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public String adaptForPreferences(@Nullable Uri value) {
    if (value == null) {
        return null;
    }
    
    return value.toString();
}
 
Example 9
Source File: GlideBigLoader.java    From ImageLoader with Apache License 2.0 5 votes vote down vote up
@Override
public void loadImage(final Uri uri) {
    final String url = uri.toString();
    Log.w("load big image:",url);
    final String finalUrl = url;

    executor.execute(new Runnable() {
        @Override
        public void run() {
            try {
             File resource =    mRequestManager
                        .asFile()
                        .load(new ProgressableGlideUrl(finalUrl))
                        .submit().get();
                if(resource.exists() && resource.isFile() && resource.length() > 100){
                    Log.i("glide onResourceReady","onResourceReady  --"+ resource.getAbsolutePath());
                    EventBus.getDefault().post(new CacheHitEvent(resource, finalUrl));
                }else {
                    Log.w(" glide onloadfailed","onLoadFailed  --"+ finalUrl);
                    EventBus.getDefault().post(new ErrorEvent(finalUrl));
                }
            }catch (Throwable throwable){
                throwable.printStackTrace();
                EventBus.getDefault().post(new ErrorEvent(finalUrl));

            }
        }
    });
}
 
Example 10
Source File: ApksBackupStorage.java    From SAI with GNU General Public License v3.0 5 votes vote down vote up
@Override
public InputStream getBackupIcon(Uri iconUri) throws Exception {
    if (iconUri.equals(EMPTY_ICON)) {
        return getContext().getAssets().open("placeholder_app_icon.png");
    }

    Pair<File, Uri> cachedIconFileAndBackupUri = unwrapIconUri(iconUri);
    File cachedIconFile = cachedIconFileAndBackupUri.first;
    if (cachedIconFile.exists()) {
        try {
            return new FileInputStream(cachedIconFile);
        } catch (IOException e) {
            Log.w(TAG, "Unable to open cached icon file", e);
        }
    }

    try (ZipInputStream zipInputStream = new ZipInputStream(openFileInputStream(cachedIconFileAndBackupUri.second))) {
        ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            if (zipEntry.getName().equals(SaiExportedAppMeta.ICON_FILE) || zipEntry.getName().equals(SaiExportedAppMeta2.ICON_FILE)) {
                return zipInputStream;
            }
        }
    }

    throw new IOException("Icon gone for icon uri " + iconUri.toString());
}
 
Example 11
Source File: MainActivity.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public static String getFilePathFromURI(Context context, Uri uri) {
	return uri.toString();
	/*String scheme = uri.getScheme();
	if (scheme.equals("file")) {
	    return uri.getPath(); // uri.getLastPathSegment();
	} else if (scheme.equals("content")) {
		Cursor cursor = null;
		try {
			//String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
			//        + MediaStore.Files.FileColumns.MEDIA_TYPE_NONE;
			//String i = MediaStore.Files.FileColumns.DATA;
			String[] proj = { MediaStore.Images.Media.DATA };
			cursor = context.getContentResolver().query(uri, proj, null, null, null);
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			String path = cursor.getString(column_index);
			if (path == null) {
				return uri.getPath();
			}
			return path;
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
    } else {
    	return uri.getPath();
    }*/
}
 
Example 12
Source File: SsManifestParser.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SsManifest parse(Uri uri, InputStream inputStream) throws IOException {
  try {
    XmlPullParser xmlParser = xmlParserFactory.newPullParser();
    xmlParser.setInput(inputStream, null);
    SmoothStreamingMediaParser smoothStreamingMediaParser =
        new SmoothStreamingMediaParser(null, uri.toString());
    return (SsManifest) smoothStreamingMediaParser.parse(xmlParser);
  } catch (XmlPullParserException e) {
    throw new ParserException(e);
  }
}
 
Example 13
Source File: PrivateActivity.java    From SimplicityBrowser with MIT License 5 votes vote down vote up
@Override
protected void onNewIntent(Intent intent) {
    setIntent(intent);
    if (intent.getData() != null) {
        final Uri intentUriData = intent.getData();
        UrlCleaner = intentUriData.toString();
        mWebView.loadUrl(UrlCleaner, extraHeaders);
    }else{
        mWebView.loadUrl("about:blank");
    }

}
 
Example 14
Source File: FileUtils.java    From AndJie with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true if uri is a media uri.
 * 
 * @param uri
 * @return
 */
public static boolean isMediaUri(Uri uri) {
	String uriString = uri.toString();
	if (uriString.startsWith(Audio.Media.INTERNAL_CONTENT_URI.toString())
			|| uriString.startsWith(Audio.Media.EXTERNAL_CONTENT_URI
					.toString())
			|| uriString.startsWith(Video.Media.INTERNAL_CONTENT_URI
					.toString())
			|| uriString.startsWith(Video.Media.EXTERNAL_CONTENT_URI
					.toString())) {
		return true;
	} else {
		return false;
	}
}
 
Example 15
Source File: ActionFile.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
private static String generateDownloadId(Uri uri, @Nullable String customCacheKey) {
  return customCacheKey != null ? customCacheKey : uri.toString();
}
 
Example 16
Source File: WXPageActivity.java    From yanxuan-weex-demo with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_wxpage);
  mContainer = (ViewGroup) findViewById(R.id.container);
  mProgressBar = (ProgressBar) findViewById(R.id.progress);
  mTipView = (TextView) findViewById(R.id.index_tip);

  Intent intent = getIntent();
  Uri uri = intent.getData();
  String from = intent.getStringExtra("from");
  mFromSplash = "splash".equals(from);

  if (uri == null) {
    uri = Uri.parse("{}");
  }
  if (uri != null) {
    try {
      JSONObject initData = new JSONObject(uri.toString());
      String bundleUrl = initData.optString("WeexBundle", null);
      if (bundleUrl != null) {
        mUri = Uri.parse(bundleUrl);
      }

      String ws = initData.optString("Ws", null);
      if (!TextUtils.isEmpty(ws)) {
        mHotReloadManager = new HotReloadManager(ws, new HotReloadManager.ActionListener() {
          @Override
          public void reload() {
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                Toast.makeText(WXPageActivity.this, "Hot reload", Toast.LENGTH_SHORT).show();
                createWeexInstance();
                renderPage();
              }
            });
          }

          @Override
          public void render(final String bundleUrl) {
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                Toast.makeText(WXPageActivity.this, "Render: " + bundleUrl, Toast.LENGTH_SHORT).show();
                createWeexInstance();
                loadUrl(bundleUrl);
              }
            });
          }
        });
      } else {
        WXLogUtils.w("Weex", "can not get hot reload config");
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  if (mUri == null) {
    mUri = Uri.parse(AppConfig.getLaunchUrl());
  }

  if (!WXSoInstallMgrSdk.isCPUSupport()) {
    mProgressBar.setVisibility(View.INVISIBLE);
    mTipView.setText(R.string.cpu_not_support_tip);
    return;
  }

  String url = getUrl(mUri);
  if (getSupportActionBar() != null) {
    getSupportActionBar().setTitle(url);
    getSupportActionBar().hide();
  }
  loadUrl(url);
}
 
Example 17
Source File: HttpDownloadActivity.java    From shortyz with GNU General Public License v3.0 4 votes vote down vote up
private void initializeDownload() {
    if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        showSDCardHelp();
        finish();

        return;
    }

    Uri u = this.getIntent()
                .getData();
    String filename = u.toString();
    filename = filename.substring(filename.lastIndexOf('/') + 1);

    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setMessage("Downloading...\n" + filename);
    dialog.setCancelable(false);

    OkHttpClient client = new OkHttpClient();

    try {
        Request request = new Request.Builder()
                .url(u.toString())
                .build();

        Response response = client.newCall(request).execute();

        if (response.code() != 200) {
            throw new IOException("Non 200 downloading...");
        }

        InputStream is = response.body().byteStream();
        File puzFile = new File(crosswordsFolder, filename);
        FileOutputStream fos = new FileOutputStream(puzFile);
        copyStream(is, fos);
        fos.close();

        Intent i = new Intent(Intent.ACTION_EDIT, Uri.fromFile(puzFile), this, PlayActivity.class);
        this.startActivity(i);
    } catch (Exception e) {
        e.printStackTrace();

        Toast t = Toast.makeText(this, "Unable to download from\n" + u.toString(), Toast.LENGTH_LONG);
        t.show();
    }

    finish();
}
 
Example 18
Source File: ChatMessagesFragment.java    From linphone-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data != null) {
        if (requestCode == ADD_PHOTO && resultCode == Activity.RESULT_OK) {
            String fileToUploadPath = null;
            if (data.getData() != null) {
                Log.i(
                        "[Chat Messages Fragment] Intent data after picking file is "
                                + data.getData().toString());
                if (data.getData().toString().contains("com.android.contacts/contacts/")) {
                    Uri cvsPath = FileUtils.getCVSPathFromLookupUri(data.getData().toString());
                    if (cvsPath != null) {
                        fileToUploadPath = cvsPath.toString();
                        Log.i("[Chat Messages Fragment] Found CVS path: " + fileToUploadPath);
                    } else {
                        // TODO Error
                        return;
                    }
                } else {
                    fileToUploadPath =
                            FileUtils.getRealPathFromURI(getActivity(), data.getData());
                    Log.i(
                            "[Chat Messages Fragment] Resolved path for data is: "
                                    + fileToUploadPath);
                }
                if (fileToUploadPath == null) {
                    fileToUploadPath = data.getData().toString();
                    Log.i(
                            "[Chat Messages Fragment] Couldn't resolve path, using as-is: "
                                    + fileToUploadPath);
                }
            } else if (mImageToUploadUri != null) {
                fileToUploadPath = mImageToUploadUri.getPath();
                Log.i(
                        "[Chat Messages Fragment] Using pre-created path for dynamic capture "
                                + fileToUploadPath);
            }

            if (fileToUploadPath.startsWith("content://")
                    || fileToUploadPath.startsWith("file://")) {
                Uri uriToParse = Uri.parse(fileToUploadPath);
                fileToUploadPath =
                        FileUtils.getFilePath(
                                getActivity().getApplicationContext(), uriToParse);
                Log.i(
                        "[Chat Messages Fragment] Path was using a content or file scheme, real path is: "
                                + fileToUploadPath);
                if (fileToUploadPath == null) {
                    Log.e(
                            "[Chat Messages Fragment] Failed to get access to file "
                                    + uriToParse.toString());
                }
            } else if (fileToUploadPath.contains("com.android.contacts/contacts/")) {
                fileToUploadPath =
                        FileUtils.getCVSPathFromLookupUri(fileToUploadPath).toString();
                Log.i(
                        "[Chat Messages Fragment] Path was using a contact scheme, real path is: "
                                + fileToUploadPath);
            }

            if (fileToUploadPath != null) {
                if (FileUtils.isExtensionImage(fileToUploadPath)) {
                    addImageToPendingList(fileToUploadPath);
                } else {
                    addFileToPendingList(fileToUploadPath);
                }
            } else {
                Log.e(
                        "[Chat Messages Fragment] Failed to get a path that we could use, aborting attachment");
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    } else {
        if (FileUtils.isExtensionImage(mImageToUploadUri.getPath())) {
            File file = new File(mImageToUploadUri.getPath());
            if (file.exists()) {
                addImageToPendingList(mImageToUploadUri.getPath());
            }
        }
    }
}
 
Example 19
Source File: AppLauncher.java    From LaunchTime with GNU General Public License v3.0 4 votes vote down vote up
private static String makeLink(String activityName, Uri uri) {
    String uristr = "";
    if (uri != null) uristr = uri.toString();
    return makeLink(activityName, uristr);
}
 
Example 20
Source File: RingtonePickerDialog.java    From android-ringtone-picker with Apache License 2.0 2 votes vote down vote up
/**
 * Set the Uri of the ringtone show as selected when dialog shows. If the given Uri is not
 * in the ringtone list, no ringtone will displayed as selected by default. This is optional
 * parameter to set.
 *
 * @param currentRingtoneUri Uri of the ringtone.
 * @return {@link Builder}
 */
public Builder setCurrentRingtoneUri(@Nullable final Uri currentRingtoneUri) {
    if (currentRingtoneUri != null && currentRingtoneUri != Uri.EMPTY)
        mCurrentRingtoneUri = currentRingtoneUri.toString();
    return this;
}