如何在Android上用OpenWeatherMap显示基于位置的天气?

时间:2018-03-23 18:37:50

标签: android openweathermap

我使用固定位置asyncTask.execute("23.8315", "91.2868");创建了一个天气应用程序。如何让应用程序使用我的gps并根据我的位置显示天气?

代码如下

MainActivity.java

import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {



TextView cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;

Typeface weatherFont;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_main);


    weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");

    cityField = (TextView)findViewById(R.id.city_field);
    updatedField = (TextView)findViewById(R.id.updated_field);
    detailsField = (TextView)findViewById(R.id.details_field);
    currentTemperatureField = (TextView)findViewById(R.id.current_temperature_field);
    humidity_field = (TextView)findViewById(R.id.humidity_field);
    pressure_field = (TextView)findViewById(R.id.pressure_field);
    weatherIcon = (TextView)findViewById(R.id.weather_icon);
    weatherIcon.setTypeface(weatherFont);


    Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() {
        public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {

            cityField.setText(weather_city);
            updatedField.setText(weather_updatedOn);
            detailsField.setText(weather_description);
            currentTemperatureField.setText(weather_temperature);
            humidity_field.setText("Humidity: "+weather_humidity);
            pressure_field.setText("Pressure: "+weather_pressure);
            weatherIcon.setText(Html.fromHtml(weather_iconText));

        }
    });
    asyncTask.execute("23.8315", "91.2868"); //  asyncTask.execute("Latitude", "Longitude")



}

Function.java

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;


public class Function {


private static final String OPEN_WEATHER_MAP_URL =
        "http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric";

private static final String OPEN_WEATHER_MAP_API = "9b6857889076855263cfdb5707c0d00";

public static String setWeatherIcon(int actualId, long sunrise, long sunset){
    int id = actualId / 100;
    String icon = "";
    if(actualId == 800){
        long currentTime = new Date().getTime();
        if(currentTime>=sunrise && currentTime<sunset) {
            icon = "&#xf00d;";
        } else {
            icon = "&#xf02e;";
        }
    } else {
        switch(id) {
            case 2 : icon = "&#xf01e;";
                break;
            case 3 : icon = "&#xf01c;";
                break;
            case 7 : icon = "&#xf014;";
                break;
            case 8 : icon = "&#xf013;";
                break;
            case 6 : icon = "&#xf01b;";
                break;
            case 5 : icon = "&#xf019;";
                break;
        }
    }
    return icon;
}



public interface AsyncResponse {

    void processFinish(String output1, String output2, String output3, String output4, String output5, String output6, String output7, String output8);
}





public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {

    public AsyncResponse delegate = null;//Call back interface

    public placeIdTask(AsyncResponse asyncResponse) {
        delegate = asyncResponse;//Assigning call back interfacethrough constructor
    }

    @Override
    protected JSONObject doInBackground(String... params) {

        JSONObject jsonWeather = null;
        try {
            jsonWeather = getWeatherJSON(params[0], params[1]);
        } catch (Exception e) {
            Log.d("Error", "Cannot process JSON results", e);
        }


        return jsonWeather;
    }

    @Override
    protected void onPostExecute(JSONObject json) {
        try {
            if(json != null){
                JSONObject details = json.getJSONArray("weather").getJSONObject(0);
                JSONObject main = json.getJSONObject("main");
                DateFormat df = DateFormat.getDateTimeInstance();


                String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
                String description = details.getString("description").toUpperCase(Locale.US);
                String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
                String humidity = main.getString("humidity") + "%";
                String pressure = main.getString("pressure") + " hPa";
                String updatedOn = df.format(new Date(json.getLong("dt")*1000));
                String iconText = setWeatherIcon(details.getInt("id"),
                        json.getJSONObject("sys").getLong("sunrise") * 1000,
                        json.getJSONObject("sys").getLong("sunset") * 1000);

                delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn, iconText, ""+ (json.getJSONObject("sys").getLong("sunrise") * 1000));

            }
        } catch (JSONException e) {
            //Log.e(LOG_TAG, "Cannot process JSON results", e);
        }



    }
}






public static JSONObject getWeatherJSON(String lat, String lon){
    try {
        URL url = new URL(String.format(OPEN_WEATHER_MAP_URL, lat, lon));
        HttpURLConnection connection =
                (HttpURLConnection)url.openConnection();

        connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));

        StringBuffer json = new StringBuffer(1024);
        String tmp="";
        while((tmp=reader.readLine())!=null)
            json.append(tmp).append("\n");
        reader.close();

        JSONObject data = new JSONObject(json.toString());

        // This value will be 404 if the request was not
        // successful
        if(data.getInt("cod") != 200){
            return null;
        }

        return data;
    }catch(Exception e){
        return null;
    }
}

}

MainActivity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3F51B5"
android:padding="20dp">

<TextView
    android:id="@+id/city_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:textColor="#FFFFFF"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/updated_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/city_field"
    android:layout_centerHorizontal="true"
    android:textColor="#FFFFFF"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textSize="13sp" />

<TextView
    android:id="@+id/weather_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:textColor="#FFFFFF"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="90sp"
    />

<TextView
    android:id="@+id/current_temperature_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:textColor="#FFFFFF"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="50sp" />

<TextView
    android:id="@+id/details_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/weather_icon"
    android:layout_centerHorizontal="true"
    android:textColor="#FFFFFF"
    android:textAppearance="?android:attr/textAppearanceMedium"
    />
<TextView
    android:id="@+id/humidity_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/details_field"
    android:layout_centerHorizontal="true"
    android:textColor="#FFFFFF"
    android:textAppearance="?android:attr/textAppearanceMedium"
    />
<TextView
    android:id="@+id/pressure_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/humidity_field"
    android:layout_centerHorizontal="true"
    android:textColor="#FFFFFF"
    android:textAppearance="?android:attr/textAppearanceMedium"
    />

1 个答案:

答案 0 :(得分:1)

您需要使用具有适当权限的位置管理器。 有了这个,你告诉你的应用程序使用GPS

import numpy as np
import vtk
from vtk.numpy_interface import dataset_adapter as da
from paraview.numpy_support import vtk_to_numpy
from paraview.vtk.numpy_interface import algorithms
from paraview.vtk.numpy_interface.algorithms import sqrt as sqrt
from paraview.vtk.numpy_interface.algorithms import eigenvalue as eigenvalue

# This is a VTKCompositeDataArray
F = inputs[0].GetCellData().GetArray('F')

# Of course it does not work! Error:
#   ValueError: operands could not be broadcast together 
#   with shapes (60,3,3) #(3,3,60)
# How to solve it?
C = F.Arrays[0] * F.Arrays[0].T
Eigs = sqrt(eigenvalue(C))
output.CellData.append(Eigs, "EigenValues")

您还需要在最新版本的android中控制它的执行时间,您可以在线轻松搜索。 通过这个,你得到了你的坐标:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

这为您提供双打坐标:

location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);