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

The following examples show how to use android.net.Uri#getPathSegments() . 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: CardboardDeviceParams.java    From Cardboard with Apache License 2.0 6 votes vote down vote up
private boolean parseNfcUri(NdefRecord record) {
	Uri uri = record.toUri();
	if (uri == null) {
		return false;
	}
	if (uri.getHost().equals("v1.0.0")) {
		this.mVendor = "com.google";
		this.mModel = "cardboard";
		this.mVersion = "1.0";
		return true;
	}
	List<String> segments = uri.getPathSegments();
	if (segments.size() != 2) {
		return false;
	}
	this.mVendor = uri.getHost();
	this.mModel = ((String) segments.get(0));
	this.mVersion = ((String) segments.get(1));

	return true;
}
 
Example 2
Source File: SchemeParser.java    From mvvm-template with GNU General Public License v3.0 6 votes vote down vote up
@Nullable private static Intent getRepo(@NonNull Context context, @NonNull Uri uri) {
    List<String> segments = uri.getPathSegments();
    if (segments == null || segments.size() < 2 || segments.size() > 3) return null;
    String owner = segments.get(0);
    String repoName = segments.get(1);
    if (!InputHelper.isEmpty(repoName)) {
        repoName = repoName.replace(".git", "");
    }
    if (segments.size() == 3) {
        String lastPath = uri.getLastPathSegment();
        if ("network".equalsIgnoreCase(lastPath)) {
            return RepoDetailActivity.createIntent(context, repoName, owner, Tab.CODE, 3);
        } else if ("stargazers".equalsIgnoreCase(lastPath)) {
            return RepoDetailActivity.createIntent(context, repoName, owner, Tab.CODE, 2);
        } else if ("watchers".equalsIgnoreCase(lastPath)) {
            return RepoDetailActivity.createIntent(context, repoName, owner, Tab.CODE, 1);
        } else {
            return null;
        }
    } else {
        return RepoDetailActivity.createIntent(context, repoName, owner);
    }
}
 
Example 3
Source File: Logger.java    From nRF-Logger-API with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns the log session object. The given Uri must points session log entries:
 * .../session/#, .../session/[KEY]/[NUMBER], or both with ./log appended.
 * For Uris not matching these patterns a {@link LocalLogSession} object will be created.
 *
 * @param context the application context.
 * @param uri     the session uri.
 * @return The log session, or <code>null</code>.
 */
@Nullable
public static ILogSession openSession(@NonNull final Context context, @Nullable final Uri uri) {
	if (uri == null)
		return null;

	final int match = mUriMatcher.match(uri);
	switch (match) {
		case SESSION_ID:
		case SESSION_KEY_NUMBER:
			return new LogSession(context, uri);
		case SESSION_ID_LOG:
		case SESSION_KEY_NUMBER_LOG:
			// we have to cut the last part from the Uri
			final Uri.Builder builder = LogContract.Session.CONTENT_URI.buildUpon();
			final List<String> segments = uri.getPathSegments();
			for (int i = 1; i < segments.size() - 1; ++i) {
				builder.appendEncodedPath(segments.get(i));
			}
			return new LogSession(context, builder.build());
		default:
			return new LocalLogSession(context, uri);
	}
}
 
Example 4
Source File: DocumentMetadata.java    From samba-documents-provider with GNU General Public License v3.0 6 votes vote down vote up
public static DocumentMetadata fromUri(Uri uri, SmbClient client) throws IOException {
final List<String> pathSegments = uri.getPathSegments();
if (pathSegments.isEmpty()) {
  throw new UnsupportedOperationException("Can't load metadata for workgroup or server.");
}

final StructStat stat = client.stat(uri.toString());
  final DirectoryEntry entry = new DirectoryEntry(
      OsConstants.S_ISDIR(stat.st_mode) ? DirectoryEntry.DIR : DirectoryEntry.FILE,
      "",
      uri.getLastPathSegment());
  final DocumentMetadata metadata = new DocumentMetadata(uri, entry);
  metadata.mStat.set(stat);

  return metadata;
}
 
Example 5
Source File: LoadWonGameListTask.java    From SteamGifts with MIT License 5 votes vote down vote up
@Override
protected IEndlessAdaptable load(Element element) {
    Element firstColumn = element.select(".table__column--width-fill").first();
    Element link = firstColumn.select("a.table__column__heading").first();

    Uri linkUri = Uri.parse(link.attr("href"));
    String giveawayLink = linkUri.getPathSegments().get(1);
    String giveawayName = linkUri.getPathSegments().get(2);

    Giveaway giveaway = new Giveaway(giveawayLink);
    giveaway.setName(giveawayName);
    giveaway.setTitle(link.text());


    Element image = element.select(".global__image-inner-wrap").first();
    if (image != null) {
        Uri uri = Uri.parse(Utils.extractAvatar(image.attr("style")));
        List<String> pathSegments = uri.getPathSegments();
        if (pathSegments.size() >= 3) {
            giveaway.setGame(new Game("apps".equals(pathSegments.get(1)) ? Game.Type.APP : Game.Type.SUB, Integer.parseInt(pathSegments.get(2))));
        }
    }

    giveaway.setPoints(-1);
    giveaway.setEntries(-1);
    Element end = firstColumn.select("span").first();
    giveaway.setEndTime(Integer.valueOf(end.attr("data-timestamp")), end.parent().text().trim());

    // Has any feedback option been picked yet?
    // If so, this would be == 1, 0 hidden items implies both feedback options are currently available to be picked.
    giveaway.setEntered(element.select(".table__gift-feedback-awaiting-reply.is-hidden").size() == 0);

    return giveaway;
}
 
Example 6
Source File: Util.java    From nono-android with GNU General Public License v3.0 5 votes vote down vote up
private static String getDocumentId(Uri documentUri) {
    final List<String> paths = documentUri.getPathSegments();
    if (paths.size() < 2) {
        throw new IllegalArgumentException("Not a document: " + documentUri);
    }
    if (!PATH_DOCUMENT.equals(paths.get(0))) {
        throw new IllegalArgumentException("Not a document: " + documentUri);
    }
    return paths.get(1);
}
 
Example 7
Source File: DocumentsContract.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the {@link Root#COLUMN_ROOT_ID} from the given URI.
 */
public static String getRootId(Uri rootUri) {
    final List<String> paths = rootUri.getPathSegments();
    if (paths.size() >= 2 && PATH_ROOT.equals(paths.get(0))) {
        return paths.get(1);
    }
    throw new IllegalArgumentException("Invalid URI: " + rootUri);
}
 
Example 8
Source File: DocumentsContract.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the {@link Root#COLUMN_ROOT_ID} from the given URI.
 */
public static String getRootId(Uri rootUri) {
    final List<String> paths = rootUri.getPathSegments();
    if (paths.size() >= 2 && PATH_ROOT.equals(paths.get(0))) {
        return paths.get(1);
    }
    throw new IllegalArgumentException("Invalid URI: " + rootUri);
}
 
Example 9
Source File: CustomTabToolbar.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private static String parsePublisherNameFromUrl(String url) {
    // TODO(ianwen): Make it generic to parse url from URI path. http://crbug.com/599298
    // The url should look like: https://www.google.com/amp/s/www.nyt.com/ampthml/blogs.html
    // or https://www.google.com/amp/www.nyt.com/ampthml/blogs.html.
    Uri uri = Uri.parse(url);
    List<String> segments = uri.getPathSegments();
    if (segments.size() >= 3) {
        if (segments.get(1).length() > 1) return segments.get(1);
        return segments.get(2);
    }
    return url;
}
 
Example 10
Source File: AttachmentId.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
static public @Nullable AttachmentId fromUri(Uri uri) {
    try {
        if (null != uri && uri.toString().startsWith("chatsession://")) {
            List<String> segments = uri.getPathSegments();
            if (segments.size() == 2) {
                AttachmentId id = new AttachmentId(Long.parseLong(segments.get(0)), Long.parseLong(segments.get(1)));
                return id;
            }
        }
    } catch (Exception e) {
        ALog.e("AttachmentId", e);
    }
    return null;
}
 
Example 11
Source File: PullsIssuesParser.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
public static PullsIssuesParser getForPullRequest(@NonNull String url) {
    Uri uri = Uri.parse(url);
    List<String> segments = uri.getPathSegments();
    if (segments == null || segments.size() < 3) return null;
    String owner = null;
    String repo = null;
    String number = null;
    if (segments.size() > 3) {
        if (("pull".equals(segments.get(2)) || "pulls".equals(segments.get(2)))) {
            owner = segments.get(0);
            repo = segments.get(1);
            number = segments.get(3);
        } else if (("pull".equals(segments.get(3)) || "pulls".equals(segments.get(3))) && segments.size() > 4) {
            owner = segments.get(1);
            repo = segments.get(2);
            number = segments.get(4);
        } else {
            return null;
        }
    }
    if (InputHelper.isEmpty(number)) return null;
    int issueNumber;
    try {
        issueNumber = Integer.parseInt(number);
    } catch (NumberFormatException nfe) {
        return null;
    }
    if (issueNumber < 1) return null;
    PullsIssuesParser model = new PullsIssuesParser();
    model.setLogin(owner);
    model.setRepoId(repo);
    model.setNumber(issueNumber);
    return model;
}
 
Example 12
Source File: NewDevDbApi.java    From 4pdaClient-plus with Apache License 2.0 5 votes vote down vote up
public static DevCatalog getCatalog(String url) throws ShowInBrowserException {
    Matcher m = Pattern.compile("4pda.ru/devdb", Pattern.CASE_INSENSITIVE).matcher(url);
    if (!m.find())
        throw new ShowInBrowserException("Не умею обрабаывать ссылки такого типа!", url);

    Uri uri = Uri.parse(url);
    DevCatalog root = new DevCatalog("-1", "DevDb").setType(DevCatalog.ROOT);
    if (uri.getPathSegments() == null || uri.getPathSegments().size() <= 0)
        return root;

    String title = uri.getPathSegments().get(0);
    switch (uri.getPathSegments().get(0).toLowerCase()) {
        case "phone":
            title = "Сотовые телефоны";
            break;
        case "ebook":
            title = "Электронные книги";
            break;
        case "pad":
            title = "Планшеты";
            break;
        case "smartwatch":
            title = "Смарт часы";
        default:
            return root;
    }
    DevCatalog devType = new DevCatalog("https://4pda.ru/devdb/" + uri.getPathSegments().get(0), title)
            .setType(DevCatalog.DEVICE_TYPE);
    devType.setParent(root);
    if (uri.getPathSegments().size() < 2) {
        return devType;
    }
    DevCatalog catalog = new DevCatalog(url, uri.getPathSegments().get(1));
    catalog.setType(DevCatalog.DEVICE_BRAND);
    catalog.setParent(devType);
    return catalog;

}
 
Example 13
Source File: UrlUtils.java    From YCAudioPlayer with Apache License 2.0 4 votes vote down vote up
/**
 * 拼接字符串
 * @param url                       url
 * @param map                       map集合
 * @return
 */
public static String getUrl(String url, HashMap<String, String> map){
    if(TextUtils.isEmpty(url)){
        return null;
    }
    //解析一个url
    Uri uri = Uri.parse(url);
    // 完整的url信息
    String urlStr = uri.toString();
    Log.e( "UrlUtils","url: " + urlStr);
    // scheme部分
    String scheme = uri.getScheme();
    Log.e( "UrlUtils","scheme: " + scheme);
    // host部分
    String host = uri.getHost();
    Log.e( "UrlUtils","host: " + host);
    //port部分
    int port = uri.getPort();
    Log.e( "UrlUtils","port: " + port);
    // 访问路劲
    String path = uri.getPath();
    Log.e( "UrlUtils","path: " + path);
    List<String> pathSegments = uri.getPathSegments();
    Log.e( "UrlUtils","pathSegments: " + pathSegments.toString());
    // Query部分
    String query = uri.getQuery();
    Log.e( "UrlUtils","query: " + query);
    //获取此URI的解码权限部分。对于服务器地址,权限的结构如下:Examples: "google.com", "[email protected]:80"
    String authority = uri.getAuthority();
    Log.e( "UrlUtils","authority: " + authority);
    //从权限获取已解码的用户信息。例如,如果权限为“任何人@google.com”,此方法将返回“任何人”。
    String userInfo = uri.getUserInfo();
    Log.e( "UrlUtils","userInfo: " + userInfo);


    //UrlUtils: url: https://m.dev.haowumc.com/app/financialManagement
    //UrlUtils: scheme: https
    //UrlUtils: host: m.dev.haowumc.com
    //UrlUtils: port: -1
    //UrlUtils: path: /app/financialManagement
    //UrlUtils: pathSegments: [app, financialManagement]
    //UrlUtils: query: null
    //UrlUtils: authority: m.dev.haowumc.com
    //UrlUtils: userInfo: null

    Uri.Builder builder = uri.buildUpon();
    if (map != null && map.size() > 0) {
        //使用迭代器进行遍历
        for (Object o : map.entrySet()) {
            Map.Entry entry = (Map.Entry) o;
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            //对键和值进行编码,然后将参数追加到查询字符串中。
            builder.appendQueryParameter(key, value);
        }
    }
    return builder.toString();
}
 
Example 14
Source File: BitmapLoadTaskInstance.java    From FimiX8-RE with MIT License 4 votes vote down vote up
public Bitmap decode(Context context, Uri uri) throws Exception {
    Bitmap bitmap;
    String uriString = uri.toString();
    Options options = new Options();
    options.inPreferredConfig = Config.RGB_565;
    if (uriString.startsWith("android.resource://")) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            res = context.getPackageManager().getResourcesForApplication(packageName);
        }
        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && ((String) segments.get(0)).equals("drawable")) {
            id = res.getIdentifier((String) segments.get(1), "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly((CharSequence) segments.get(0))) {
            try {
                id = Integer.parseInt((String) segments.get(0));
            } catch (NumberFormatException e) {
            }
        }
        bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
    } else if (uriString.startsWith("file:///android_asset/")) {
        bitmap = BitmapFactory.decodeStream(context.getAssets().open(uriString.substring("file:///android_asset/".length())), (Rect) null, options);
    } else if (uriString.startsWith("file://")) {
        bitmap = BitmapFactory.decodeFile(uriString.substring("file://".length()), options);
    } else {
        InputStream inputStream = null;
        try {
            inputStream = context.getContentResolver().openInputStream(uri);
            bitmap = BitmapFactory.decodeStream(inputStream, (Rect) null, options);
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e2) {
                }
            }
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e3) {
                }
            }
        }
    }
    if (bitmap != null) {
        return bitmap;
    }
    throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported");
}
 
Example 15
Source File: MultiredditPostListURL.java    From RedReader with GNU General Public License v3.0 4 votes vote down vote up
public static MultiredditPostListURL parse(final Uri uri) {

		Integer limit = null;
		String before = null, after = null;

		for(final String parameterKey : General.getUriQueryParameterNames(uri)) {

			if(parameterKey.equalsIgnoreCase("after")) {
				after = uri.getQueryParameter(parameterKey);

			} else if(parameterKey.equalsIgnoreCase("before")) {
				before = uri.getQueryParameter(parameterKey);

			} else if(parameterKey.equalsIgnoreCase("limit")) {
				try {
					limit = Integer.parseInt(uri.getQueryParameter(parameterKey));
				} catch(Throwable ignored) {}

			}
		}

		final String[] pathSegments;
		{
			final List<String> pathSegmentsList = uri.getPathSegments();

			final ArrayList<String> pathSegmentsFiltered = new ArrayList<>(pathSegmentsList.size());
			for(String segment : pathSegmentsList) {

				while(General.asciiLowercase(segment).endsWith(".json") || General.asciiLowercase(segment).endsWith(".xml")) {
					segment = segment.substring(0, segment.lastIndexOf('.'));
				}

				if(segment.length() > 0) {
					pathSegmentsFiltered.add(segment);
				}
			}

			pathSegments = pathSegmentsFiltered.toArray(new String[pathSegmentsFiltered.size()]);
		}

		final PostSort order;
		if(pathSegments.length > 0) {
			order = PostSort.parse(pathSegments[pathSegments.length - 1], uri.getQueryParameter("t"));
		} else {
			order = null;
		}

		if(pathSegments.length < 3) {
			return null;
		}

		if(pathSegments[0].equalsIgnoreCase("me")) {

			if(!pathSegments[1].equalsIgnoreCase("m")) {
				return null;
			}

			return new MultiredditPostListURL(
					null,
					pathSegments[2],
					order,
					limit,
					before,
					after);

		} else {

			if(!pathSegments[0].equalsIgnoreCase("user")
					|| !pathSegments[2].equalsIgnoreCase("m")
					|| pathSegments.length < 4) {

				return null;
			}

			return new MultiredditPostListURL(
					pathSegments[1],
					pathSegments[3],
					order,
					limit,
					before,
					after);
		}
	}
 
Example 16
Source File: CachedImageFileProvider.java    From Onosendai with Apache License 2.0 4 votes vote down vote up
protected static String baseName (final Uri uri) {
	final List<String> segs = uri.getPathSegments();
	return segs.get(segs.size() - 1);
}
 
Example 17
Source File: AppbarJsBridge.java    From letv with Apache License 2.0 4 votes vote down vote up
public void invoke(String str) {
    f.b(f.d, "-->invoke : url = " + str);
    Uri parse = Uri.parse(str);
    String host = parse.getHost();
    f.b(f.d, "-->invoke : hostAsMethodName = " + host);
    if (!TextUtils.isEmpty(host)) {
        int i;
        List pathSegments = parse.getPathSegments();
        String str2 = null;
        if (pathSegments == null || pathSegments.size() <= 0) {
            i = 0;
        } else {
            i = Util.parseIntValue((String) pathSegments.get(0));
            if (pathSegments.size() > 1) {
                str2 = (String) pathSegments.get(1);
            }
        }
        f.b(f.d, "-->invoke : seqid = " + i + " callbackName = " + str2);
        if (host.equals("callBatch")) {
            try {
                JSONArray jSONArray = new JSONArray(parse.getQueryParameter(a.f));
                int length = jSONArray.length();
                for (int i2 = 0; i2 < length; i2++) {
                    JSONObject jSONObject = jSONArray.getJSONObject(i2);
                    String string = jSONObject.getString("method");
                    int i3 = jSONObject.getInt("seqid");
                    String optString = jSONObject.optString(a.c);
                    JSONObject jSONObject2 = jSONObject.getJSONObject("args");
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(JS_BRIDGE_SCHEME).append(string).append("/").append(i3).append("/").append(!TextUtils.isEmpty(optString) ? optString : "").append("?");
                    if (jSONObject2 != null) {
                        Iterator keys = jSONObject2.keys();
                        while (keys.hasNext()) {
                            String str3 = (String) keys.next();
                            stringBuilder.append(str3).append(SearchCriteria.EQ).append(Uri.encode(Uri.decode(jSONObject2.getString(str3)))).append("&");
                        }
                    }
                    a(Uri.parse(stringBuilder.toString()), string, i3, optString);
                }
                return;
            } catch (Exception e) {
                if (!TextUtils.isEmpty(str2)) {
                    responseFail(str2, i, host, -5);
                    return;
                }
                return;
            }
        }
        a(parse, host, i, str2);
    }
}
 
Example 18
Source File: RepoProvider.java    From fdroidclient with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This method decides what repo a URL belongs to by iteratively removing path fragments and
 * checking if it belongs to a repo or not. It will match the most specific repository which
 * could serve the file at the given URL.
 * <p>
 * For any given HTTP resource requested by F-Droid, it should belong to a repository.
 * Whether that resource is an index.jar, an icon, or a .apk file, they all belong to a
 * repository. Therefore, that repository must exist in the database. The way to find out
 * which repository a particular URL came from requires some consideration:
 * <li>Repositories can exist at particular paths on a server (e.g. /fdroid/repo)
 * <li>Individual files can exist at a more specific path on the repo (e.g.
 * /fdroid/repo/icons/org.fdroid.fdroid.png)</li>
 * <p>
 * So for a given URL "/fdroid/repo/icons/org.fdroid.fdroid.png" we don't actually know
 * whether it is for the file "org.fdroid.fdroid.png" at repository "/fdroid/repo/icons" or
 * the file "icons/org.fdroid.fdroid.png" at the repository at "/fdroid/repo".
 */
@Nullable
public static Repo findByUrl(Context context, Uri uri, String[] projection) {
    Uri withoutQuery = uri.buildUpon().query(null).build();
    Repo repo = findByAddress(context, withoutQuery.toString(), projection);

    // Take a copy of this, because the result of getPathSegments() is an AbstractList
    // which doesn't support the remove() operation.
    List<String> pathSegments = new ArrayList<>(withoutQuery.getPathSegments());

    boolean haveTriedWithoutPath = false;
    while (repo == null && !haveTriedWithoutPath) {
        if (pathSegments.isEmpty()) {
            haveTriedWithoutPath = true;
        } else {
            pathSegments.remove(pathSegments.size() - 1);
            withoutQuery = withoutQuery.buildUpon().path(TextUtils.join("/", pathSegments)).build();
        }
        repo = findByAddress(context, withoutQuery.toString(), projection);
    }
    return repo;
}
 
Example 19
Source File: SchemeSecondActivity.java    From YCAudioPlayer with Apache License 2.0 4 votes vote down vote up
/**
 * 协议部分,随便设置 yc://app/?page=main
 */

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Uri uri = getIntent().getData();
    if (uri != null) {
        //解析一个url
        // 完整的url信息
        String urlStr = uri.toString();
        Log.e( "UrlUtils","url: " + urlStr);
        // scheme部分
        String scheme = uri.getScheme();
        Log.e( "UrlUtils","scheme: " + scheme);
        // host部分
        String host = uri.getHost();
        Log.e( "UrlUtils","host: " + host);
        //port部分
        int port = uri.getPort();
        Log.e( "UrlUtils","port: " + port);
        // 访问路劲
        String path = uri.getPath();
        Log.e( "UrlUtils","path: " + path);
        List<String> pathSegments = uri.getPathSegments();
        Log.e( "UrlUtils","pathSegments: " + pathSegments.toString());
        // Query部分
        String query = uri.getQuery();
        Log.e( "UrlUtils","query: " + query);
        //获取此URI的解码权限部分。对于服务器地址,权限的结构如下:Examples: "google.com", "[email protected]:80"
        String authority = uri.getAuthority();
        Log.e( "UrlUtils","authority: " + authority);
        //从权限获取已解码的用户信息。例如,如果权限为“任何人@google.com”,此方法将返回“任何人”。
        String userInfo = uri.getUserInfo();
        Log.e( "UrlUtils","userInfo: " + userInfo);
        //获取指定参数值
        String page = uri.getQueryParameter("page");
        Log.e( "UrlUtils","main: " + page);
        //UrlUtils: url: https://m.dev.haowumc.com/app/financialManagement
        //UrlUtils: scheme: https
        //UrlUtils: host: m.dev.haowumc.com
        //UrlUtils: port: -1
        //UrlUtils: path: /app/financialManagement
        //UrlUtils: pathSegments: [app, financialManagement]
        //UrlUtils: query: null
        //UrlUtils: authority: m.dev.haowumc.com
        //UrlUtils: userInfo: null

        switch (page){
            //yc://app/?page=yangchong
            case "yangchong":
                ActivityUtils.startActivity(GuideActivity.class);
                break;
            //yc://app/?page=main
            case "main":
                readGoActivity(new Intent(this,MainActivity.class),this);
                break;
            //yc://app/?page=setting
            case "setting":
                readGoActivity(new Intent(this, MeSettingActivity.class),this);
                break;
        }
    }
    finish();
}
 
Example 20
Source File: SkiaImageDecoder.java    From PdfViewPager with Apache License 2.0 4 votes vote down vote up
@Override
@NonNull
public Bitmap decode(Context context, @NonNull Uri uri) throws Exception {
    String uriString = uri.toString();
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap;
    options.inPreferredConfig = bitmapConfig;
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        bitmap = BitmapFactory.decodeStream(context.getAssets().open(assetName), null, options);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        bitmap = BitmapFactory.decodeFile(uriString.substring(FILE_PREFIX.length()), options);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            bitmap = BitmapFactory.decodeStream(inputStream, null, options);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) { /* Ignore */ }
            }
        }
    }
    if (bitmap == null) {
        throw new RuntimeException(
                "Skia image region decoder returned null bitmap - image format may not be supported"
        );
    }
    return bitmap;
}