【问题标题】:convert Url to Uri将 Url 转换为 Uri
【发布时间】:2014-03-15 13:47:38
【问题描述】:

我正在开发小部件。 我想将图像(在服务器上可用)设置为小部件背景。 以下不起作用,因为 uri 没有从 URL 获取

代码:

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

【问题讨论】:

    标签: android url android-widget uri


    【解决方案1】:

    uri 没有从 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;
        } 
    

    【讨论】:

    • setImageViewUri (int viewId, Uri uri) 如果我从服务器获取,这不是设置图像。我已经把它放在了 AsynkTask 和 onpostExecute 我已经设置了remoteViews.setImageViewUri(R.id.widget_img, myUri)
    • 让我举个例子。您在 android 设备的 sdcard 上有一个图像,您使用 contentresolver 获取该图像的 uri,然后将该 uri 传递给 setImageViewUri。在这种情况下,您将很容易获得该图像。但是,如果您在本地没有图像但在服务器上有它(就像您的情况一样),您需要先使用 asynctask 下载它,如上所示,然后将该位图与视图一起使用。
    • 我很喜欢你的想法,并在 ipdate 上发布了一篇关于它的完整代码的帖子。但仍然没有图像显示为背景。stackoverflow.com/questions/22448242/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    相关资源
    最近更新 更多