You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Android应用时获取设备当前天气的方法咨询(含无API方案)

Hey there! Let's tackle your Android weather data questions step by step—since you're building an app, I'll make sure to cover practical, actionable approaches.

1. How to Get Current Weather on Android (Standard Reliable Approach)

The most stable way to fetch accurate current weather is using a third-party weather API (many offer free tiers for small-scale apps). You’ll need two core pieces: location access to grab the user’s current coordinates, and an API key from a service like OpenWeatherMap or WeatherAPI.

Here’s a quick example using Volley to pull weather data (first add Volley to your module-level build.gradle):

// Add this to build.gradle (Module level)
// implementation 'com.android.volley:volley:1.2.1'

// In your Activity/Fragment
val queue = Volley.newRequestQueue(this)
// Replace YOUR_LAT, YOUR_LON, and YOUR_API_KEY with actual values
val url = "https://api.openweathermap.org/data/2.5/weather?lat=YOUR_LAT&lon=YOUR_LON&appid=YOUR_API_KEY&units=metric"

val stringRequest = StringRequest(
    Request.Method.GET, url,
    { response ->
        // Parse the JSON response here to extract temperature, condition, humidity, etc.
        Log.d("WeatherData", "Fetched: $response")
    },
    { error ->
        Log.e("WeatherError", "Failed to load data: ${error.message}")
    })

queue.add(stringRequest)

Don’t forget to declare location permissions (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) in your manifest and request them at runtime!

2. Get Weather Without Using Any API (Unofficial & Unstable)

Fair warning: This method isn’t supported by Google or device manufacturers, so it might break across Android versions or brand skins (like Samsung One UI, Xiaomi MIUI). But if you’re set on avoiding APIs, you can try accessing the system’s built-in weather data via a Content Provider.

Some Android skins store weather data in a hidden content URI. For example, on certain Xiaomi devices, you can query this:

val weatherUri = Uri.parse("content://com.android.providers.weather/weather")
val cursor = contentResolver.query(weatherUri, null, null, null, null)
cursor?.use {
    if (it.moveToFirst()) {
        val temp = it.getString(it.getColumnIndex("temperature"))
        val condition = it.getString(it.getColumnIndex("condition"))
        Log.d("SystemWeather", "Temp: $temp°C, Condition: $condition")
    }
}

Keep in mind: The URI, column names, and availability will vary wildly between devices. Web scraping is another option, but it’s against most websites’ terms of service and prone to breaking when sites update their layout.

3. Access Device Temperature Data

Important note: Most consumer Android phones don’t have a sensor that measures ambient (outside) temperature. The sensors you can access track internal component temps (battery, CPU, etc.). If that’s what you need, here’s how to read them:

For Ambient Temperature (Rarely Available)

private lateinit var sensorManager: SensorManager
private var tempSensor: Sensor? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
    tempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) ?: run {
        Log.w("TempSensor", "No ambient temp sensor found—falling back to battery temp")
        null
    }
}

private val sensorListener = object : SensorEventListener {
    override fun onSensorChanged(event: SensorEvent?) {
        event?.let {
            if (it.sensor.type == Sensor.TYPE_AMBIENT_TEMPERATURE) {
                val temp = it.values[0]
                Log.d("DeviceTemp", "Ambient temp: $temp°C")
            }
        }
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
}

override fun onResume() {
    super.onResume()
    tempSensor?.let {
        sensorManager.registerListener(sensorListener, it, SensorManager.SENSOR_DELAY_NORMAL)
    }
}

override fun onPause() {
    super.onPause()
    sensorManager.unregisterListener(sensorListener)
}

For Battery Temperature (More Reliable)

val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val batteryTemp = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_TEMPERATURE) / 10.0f
Log.d("BatteryTemp", "Battery temp: $batteryTemp°C")

内容的提问来源于stack exchange,提问作者VISHAL VASOYA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:20:09