📜  如何在Android中构建Weather App?

📅  最后修改于: 2021-05-10 17:37:19             🧑  作者: Mango

在这个项目中,我们将构建一个天气应用程序。此应用程序将显示位置的温度。要获取天气信息,我们需要一个API。 API(应用程序编程接口)是允许应用程序使用各种组件和微服务进行交互和共享数据的函数。对于这个项目,我们将使用WeatherBit API来获取天气数据。 WeatherBit API提供了一种快速而优雅的方式来获取天气数据。请注意,我们将使用Kotlin语言实施此项目。

项目概况

在此项目中,我们将构建一个应用程序,该应用程序将找到设备的位置坐标(经度和纬度)。然后,我们将通过API密钥将此数据发送到API (稍后将看到)。该API将向我们发送JSON 从中我们将提取所需的数据,即位置的温度和所在城市。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Kotlin作为编程语言。

第2步:首先进入编码部分,您必须做一些准备工作

转到应用程序> res>可绘制文件,然后将此图像粘贴到该文件中。现在,右键单击可绘制文件夹>新建>可绘制资源文件,并将文件命名s btn_bg6 。以下是btn_bg6.xml文件的代码。

XML


    
        
            
        
    


XML


    
    
    
        
            
                
  
                
            
        
    
  


XML


  
    


Kotlin
import android.annotation.SuppressLint
import android.location.Location
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
  
class MainActivity : AppCompatActivity() {
      
    // weather url to get JSON
    var weather_url1 = ""
  
    // api id for url
    var api_id1 = "030314b750cc43e7b39e503dfe37150c"
      
    private lateinit var textView: TextView
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
          
        // link the textView in which the 
        // temperature will be displayed
        textView = findViewById(R.id.textView)
          
        // create an instance of the Fused
        // Location Provider Client
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        Log.e("lat", weather_url1)
          
        // on clicking this button function to
        // get the coordinates will be called
        btVar1.setOnClickListener {
            Log.e("lat", "onClick")
            // function to find the coordinates
            // of the last location
            obtainLocation()
        }
    }
  
    @SuppressLint("MissingPermission")
    private fun obtainLocation() {
        Log.e("lat", "function")
        // get the last location
        fusedLocationClient.lastLocation
            .addOnSuccessListener { location: Location? ->
                // get the latitude and longitude
                // and create the http URL
                weather_url1 = "https://api.weatherbit.io/v2.0/current?" + "lat=" + location?.latitude + "&lon=" + location?.longitude + "&key=" + api_id1
                Log.e("lat", weather_url1.toString())
                // this function will
                // fetch data from URL
                getTemp()
            }
    }
  
    fun getTemp() {
        // Instantiate the RequestQueue.
        val queue = Volley.newRequestQueue(this)
        val url: String = weather_url1
        Log.e("lat", url)
          
        // Request a string response 
        // from the provided URL.
        val stringReq = StringRequest(Request.Method.GET, url,
            Response.Listener { response ->
                Log.e("lat", response.toString())
                  
                // get the JSON object
                val obj = JSONObject(response)
                  
                // get the Array from obj of name - "data"
                val arr = obj.getJSONArray("data")
                Log.e("lat obj1", arr.toString())
                  
                // get the JSON object from the 
                // array at index position 0
                val obj2 = arr.getJSONObject(0)
                Log.e("lat obj2", obj2.toString())
                  
                // set the temperature and the city
                // name using getString() function
                textView.text = obj2.getString("temp") + " deg Celcius in " + obj2.getString("city_name")
            },
            // In case of any error
            Response.ErrorListener { textView!!.text = "That didn't work!" })
        queue.add(stringReq)
    }
}


步骤3:取得API金钥

要获取API密钥,只需登录 WeatherBit 并订阅当前天气数据API的免费API。这样做之后,您将收到一个API密钥,您可以继续进行。

步骤4:权限检查

为了使该应用程序正常运行,我们需要从系统中请求三个权限–

我们将在AndroidManifest.xml文件中添加使用权限代码。见下面的代码

XML格式



    
    
    
        
            
                
  
                
            
        
    
  

步骤5:建立版面

我们将添加一个按钮 TextView 在该应用程序的唯一屏幕中。当用户单击按钮时,该位置的温度和城市将显示在TextView中。请参见下面的代码:

XML格式



  
    

步骤6:获取设备的坐标

在此步骤中,我们将使用Google Play服务获取设备的最后位置–

  • 通过在SDK管理器中下载其组件来设置Google Play服务。
  • 添加依赖于为的build.gradle位置- “实施com.google.android.gms:播放服务地点:17.1.0“,该版本可能会在以后更改。
  • onCreate()方法中,创建一个Fused Location Provider Client的实例。
  • 之后,使用lastlocation()方法调用最后一个位置。请参阅步骤5之后的Kotlin代码。

步骤7:获取JSON后解析

要获取JSON,我们需要使用Volley 发出HTTP客户端请求的库

  • ‘implementation com.android.volley:volley:1.1.1’添加到gradle应用文件中。
  • 为JSON创建http。例如– “ https://api.weatherbit.io/v2.0/current?” +“纬度=” +位置?。纬度+“&lon =” +位置?。经度+“&key =” + api_id1。在这里,我们已经生成了API密钥以及位置坐标。
  • 从该URL发出请求并获取数据。

步骤8:使用MainActivity.kt文件

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

科特林

import android.annotation.SuppressLint
import android.location.Location
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
  
class MainActivity : AppCompatActivity() {
      
    // weather url to get JSON
    var weather_url1 = ""
  
    // api id for url
    var api_id1 = "030314b750cc43e7b39e503dfe37150c"
      
    private lateinit var textView: TextView
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
          
        // link the textView in which the 
        // temperature will be displayed
        textView = findViewById(R.id.textView)
          
        // create an instance of the Fused
        // Location Provider Client
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        Log.e("lat", weather_url1)
          
        // on clicking this button function to
        // get the coordinates will be called
        btVar1.setOnClickListener {
            Log.e("lat", "onClick")
            // function to find the coordinates
            // of the last location
            obtainLocation()
        }
    }
  
    @SuppressLint("MissingPermission")
    private fun obtainLocation() {
        Log.e("lat", "function")
        // get the last location
        fusedLocationClient.lastLocation
            .addOnSuccessListener { location: Location? ->
                // get the latitude and longitude
                // and create the http URL
                weather_url1 = "https://api.weatherbit.io/v2.0/current?" + "lat=" + location?.latitude + "&lon=" + location?.longitude + "&key=" + api_id1
                Log.e("lat", weather_url1.toString())
                // this function will
                // fetch data from URL
                getTemp()
            }
    }
  
    fun getTemp() {
        // Instantiate the RequestQueue.
        val queue = Volley.newRequestQueue(this)
        val url: String = weather_url1
        Log.e("lat", url)
          
        // Request a string response 
        // from the provided URL.
        val stringReq = StringRequest(Request.Method.GET, url,
            Response.Listener { response ->
                Log.e("lat", response.toString())
                  
                // get the JSON object
                val obj = JSONObject(response)
                  
                // get the Array from obj of name - "data"
                val arr = obj.getJSONArray("data")
                Log.e("lat obj1", arr.toString())
                  
                // get the JSON object from the 
                // array at index position 0
                val obj2 = arr.getJSONObject(0)
                Log.e("lat obj2", obj2.toString())
                  
                // set the temperature and the city
                // name using getString() function
                textView.text = obj2.getString("temp") + " deg Celcius in " + obj2.getString("city_name")
            },
            // In case of any error
            Response.ErrorListener { textView!!.text = "That didn't work!" })
        queue.add(stringReq)
    }
}

输出:

GitHub链接: https : //github.com/njdunk07/NJ-Weather-GFG

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