📜  如何从 URL 加载任何图像而不使用 Android 中的任何依赖项?

📅  最后修改于: 2022-05-13 01:54:34.386000             🧑  作者: Mango

如何从 URL 加载任何图像而不使用 Android 中的任何依赖项?

许多应用程序使用 Glide 和 Picasso 等第三方 API 加载图像来显示来自 Internet 的图像。这意味着此类应用程序部分依赖于这些服务来保持其正常工作。为了使应用程序更好,应该编写自己的代码而不是依赖于这些服务。在本文中,我们将向您展示如何在不使用任何外部服务的情况下轻松地在应用程序中加载图像。

分步实施

第 1 步:在 Android Studio 中创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。我们在 Kotlin 中演示了该应用程序,因此请确保在创建新项目时选择 Kotlin 作为主要语言。

第 2 步:在 AndroidManifest.xml 中添加 Internet 权限

由于图像采用 URL 的形式,应用程序将需要 Internet 权限来解析信息。



XML


XML


  
      
    
  


Kotlin
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.concurrent.Executors
  
class MainActivity : AppCompatActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Declaring and initializing the ImageView
        val imageView = findViewById(R.id.imageView)
  
        // Declaring executor to parse the URL
        val executor = Executors.newSingleThreadExecutor()
          
        // Once the executor parses the URL 
        // and receives the image, handler will load it
        // in the ImageView
        val handler = Handler(Looper.getMainLooper())
          
        // Initializing the image
        var image: Bitmap? = null
  
        // Only for Background process (can take time depending on the Internet speed)
        executor.execute {
            
             // Image URL
            val imageURL = "https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png"
              
              // Tries to get the image and post it in the ImageView
              // with the help of Handler
              try {
                val `in` = java.net.URL(imageURL).openStream()
                image = BitmapFactory.decodeStream(`in`)
  
                // Only for making changes in UI
                handler.post {
                    imageView.setImageBitmap(image)
                }
            }
              
            // If the URL doesnot point to 
              // image or any other kind of failure
            catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}


第三步:在布局中创建一个ImageView

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。

XML



  
      
    
  

第 4 步:编程从 URL 加载图像并在 ImageView 中显示

转到MainActivity.kt文件并参考以下代码。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。

科特林

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.concurrent.Executors
  
class MainActivity : AppCompatActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Declaring and initializing the ImageView
        val imageView = findViewById(R.id.imageView)
  
        // Declaring executor to parse the URL
        val executor = Executors.newSingleThreadExecutor()
          
        // Once the executor parses the URL 
        // and receives the image, handler will load it
        // in the ImageView
        val handler = Handler(Looper.getMainLooper())
          
        // Initializing the image
        var image: Bitmap? = null
  
        // Only for Background process (can take time depending on the Internet speed)
        executor.execute {
            
             // Image URL
            val imageURL = "https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png"
              
              // Tries to get the image and post it in the ImageView
              // with the help of Handler
              try {
                val `in` = java.net.URL(imageURL).openStream()
                image = BitmapFactory.decodeStream(`in`)
  
                // Only for making changes in UI
                handler.post {
                    imageView.setImageBitmap(image)
                }
            }
              
            // If the URL doesnot point to 
              // image or any other kind of failure
            catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}

输出:

我们可以看到图片加载成功。这意味着该应用程序可以按预期完美运行。

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!