android - 将 Url 转换为 Uri

标签 android url android-widget uri

我正在开发 Widget。 我想将图像(在服务器上可用)设置为小部件背景。 由于 uri 不是从 URL 获取的,因此以下内容不起作用

代码:

Uri myUri = Uri.parse("http://videodet.com/cc-content/uploads/thumbs/g45EMgnPwsciIJdOSMQt.jpg");
remoteViews.setImageViewUri(R.id.widget_img, myUri);

最佳答案

uri not getting from URL

我认为您的网址可能有问题。

我建议您尝试以下检查网址:

        URI uri = null;
        URL url = null;

方法一:

        // Create a URI from url
        try {
            uri = new URI("http://www.google.com/");
            Log.d("URI created: " + uri);
        }
        catch (URISyntaxException e) {
            Log.e("URI Syntax Error: " + e.getMessage());
        }

方法二

        // Create a URL
        try {
            url = new URL("http://www.google.com/");
            Log.d("URL created: " + url);
        }
        catch (MalformedURLException e) {
            Log.e("Malformed URL: " + e.getMessage());
        }

        // Convert a URL to a URI
        try {
            uri = url.toURI();
            Log.d("URI from URL: " + uri);
        }
        catch (URISyntaxException e) {
            Log.e("URI Syntax Error: " + e.getMessage());
        }

注意:

我想指出 setImageViewUri (int viewId, Uri uri) 是针对 Android 平台特定的内容 URI,而不是指定 Internet 资源的 URI。

您可以尝试以下方法从服务器获取位图:

    private Bitmap getImageBitmap(String url) {
            Bitmap bm = null;
            try {
                URL aURL = new URL(url);
                URLConnection conn = aURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                bm = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();
           } catch (IOException e) {
               Log.e(TAG, "Error getting bitmap", e);
           }
       return bm;
    } 

关于android - 将 Url 转换为 Uri,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22424638/

相关文章:

css - 在 HTML/CSS 模板中查找图像的位置

python - 如何根据所选条目路由到 Flask 中的 MySQL ID?

Android StackWidget 无法绑定(bind)

android - 使用 html 和 TextView 在 android 小部件上显示图像

android - 在上一个 Activity 中调用 startService 时 bindService 失败

android - 将深层链接添加到日历描述

java - 如何在java中按升序对xml代码进行排序

PHP urlencode - 仅对文件名进行编码并且不要触摸斜杠

android - 强制 Android 小部件更新

java - 从图库或照片中删除图片 android 8.0