获取没有GPS的天气信息

时间:2014-04-14 18:33:18

标签: java android gps

我无法获取天气信息with gps ..找到我的位置和天气的代码是这样的:

private boolean isRuntimePostGingerbread() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    public void loadWeathercard() {
        //Set the date
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        citylb = (TextView) findViewById(R.id.citybox);
        //Check if the custom weather place preference is enabled
        if (!sharedPrefs.getBoolean("weather_customlocationcheck", false)) {
            citylb.setText(getString(R.string.rilevamento));

            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            /**
             * Check the provider exists before registering for updates from it
             * */
            if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 0, this);

            if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, this);
            locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } else {
            //Get the custom city, refresh the city label and get the weather
            citylb.setText(sharedPrefs.getString("weather_customlocation", getString(R.string.location_null)));
            getWeather((String) citylb.getText());
        }
    }

    /**
     * Function to check if the device is online
     */
    /**
    *   Default method
    */ 

    public Boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.isConnected()){
            return true;
        // This is method suggested.. Have i use this?
        }
        return false;
    }  
    private void getWeather(String location) {
        if (isOnline()) {
            Log.d("YWeatherGetter4a", "onCreate");
            YahooWeatherUtils yahooWeatherUtils = YahooWeatherUtils.getInstance();
            yahooWeatherUtils.queryYahooWeather(getApplicationContext(), location, this); // Basta mettere la location presa dalle preferences
        } else
            Toast.makeText(getApplicationContext(), "Sorry, no connection available", Toast.LENGTH_SHORT).show();

    }
    /**
     * Rilevo la posizione attuale
     * */

    public void gotWeatherInfo(final WeatherInfo weatherInfo) {
        if (weatherInfo != null) {
            current = weatherInfo.getCurrentText().toString();
            // Converto in stringa la temperatura
            TempCurrent = String.valueOf(weatherInfo.getCurrentTempC());
            String TempHigh = String.valueOf(weatherInfo.getForecast1TempHighC());
            String TempLow = String.valueOf(weatherInfo.getForecast1TempLowC());
          //  + weatherInfo.getAtmosphereHumidity() + "%"  per l'umidit
          /* LoadWebImagesTask task = new LoadWebImagesTask();
           task.execute(

                    weatherInfo.getCurrentConditionIconURL()
            );*/
           Time oggi = new Time(Time.getCurrentTimezone());
           oggi.setToNow();
            String orariometeo = oggi.format("%k:%M");

           ImageView imgView = (ImageView)findViewById(R.id.imageview_forecast_info);
           if(current.toLowerCase().contains("sunny")){
               current = getResources().getString(R.string.sunny);
               Drawable myDrawable = getResources().getDrawable(R.drawable.sunny);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("partly cloudy")) {
               current = getResources().getString(R.string.partlycloudy);
               Drawable myDrawable = getResources().getDrawable(R.drawable.partlycloudy);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("mostly cloudy")) {
               current = getResources().getString(R.string.cloudy);
               Drawable myDrawable = getResources().getDrawable(R.drawable.mostlycloudy);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("fair")) {
               current = getResources().getString(R.string.fair);
               Drawable myDrawable = getResources().getDrawable(R.drawable.clear);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("showers")) {
               current = getResources().getString(R.string.showers);
               Drawable myDrawable = getResources().getDrawable(R.drawable.rain);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("foggy")) {
               current = getResources().getString(R.string.foggy);
               Drawable myDrawable = getResources().getDrawable(R.drawable.mist);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("thunderstorms")) {
               current = getResources().getString(R.string.thunderstorms);
               Drawable myDrawable = getResources().getDrawable(R.drawable.thunderstorm);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("thundershowers")) {
               current = getResources().getString(R.string.thundershowers);
               Drawable myDrawable = getResources().getDrawable(R.drawable.storm);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("freezingdrizzle") || current.toLowerCase().contains("hail")) {
               current = getResources().getString(R.string.freezingdrizzle);
               Drawable myDrawable = getResources().getDrawable(R.drawable.freezingdrizzle);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("lightsnowshowers")) {
               current = getResources().getString(R.string.lightsnowshowers);
               Drawable myDrawable = getResources().getDrawable(R.drawable.chanceofsnow);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("clear") || current.toLowerCase().contains("hot")) {
               current = getResources().getString(R.string.clear);
               Drawable myDrawable = getResources().getDrawable(R.drawable.clear);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("cloudy")) {
               current = getResources().getString(R.string.cloudy);
               Drawable myDrawable = getResources().getDrawable(R.drawable.cloudy);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("snow")) {
               current = getResources().getString(R.string.snow);
               Drawable myDrawable = getResources().getDrawable(R.drawable.snow);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("drizzle")) {
               current = getResources().getString(R.string.drizzle);
               Drawable myDrawable = getResources().getDrawable(R.drawable.lightrain);
               imgView.setImageDrawable(myDrawable);

           } else if (current.toLowerCase().contains("rain") || current.toLowerCase().contains("showers")) {
               current = getResources().getString(R.string.showers);
               Drawable myDrawable = getResources().getDrawable(R.drawable.rain);
               imgView.setImageDrawable(myDrawable);

           }

           temperaturenow = (TextView) findViewById(R.id.temperaturenow);
           temperaturenow.setText(current + " ");

           temperatura = (TextView)findViewById(R.id.temperatura);
           temperatura.setText(TempCurrent + "°");

           maxmin = (TextView)findViewById(R.id.maxmin);
           maxmin.setText(Html.fromHtml(TempHigh + "/" +"<small>"+TempLow+"</small>" +"°C"));

           imgView.setOnClickListener(new View.OnClickListener(){
               @Override
               public void onClick(View view){
                   boolean installed  =   appInstalledOrNot("com.yahoo.mobile.client.android.weather");  
                    if(installed) {
                        String meteoinfo = weatherInfo.getWeatherurl();
                        //This intent will help you to launch if the package is already installed
                        Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.yahoo.mobile.client.android.weather");
                        LaunchIntent.putExtra(SearchManager.QUERY, meteoinfo);
                        startActivity(LaunchIntent);    

                    } else {
                       Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(weatherInfo.getWeatherurl()));
                       startActivity(i);
                    }
               }
           });
        } else {
            Toast.makeText(getApplicationContext(), "Sorry, no result returned", Toast.LENGTH_SHORT).show();
        }
    }

    class LoadWebImagesTask extends AsyncTask<String, Void, Bitmap[]> {

        @Override
        protected Bitmap[] doInBackground(String... params) {
            Bitmap[] res = new Bitmap[6];
            res[0] = ImageUtils.getBitmapFromWeb(params[0]);

            return res;
        }

        @Override
        protected void onPostExecute(Bitmap[] results) {
            super.onPostExecute(results);
            citylb.setCompoundDrawablesWithIntrinsicBounds(null, null, null, new BitmapDrawable(getResources(), results[0]));

        }

    }


    public void loadWeathercard1() {
        //Set the date
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        citylbpref = (TextView) findViewById(R.id.cityboxpref);
        //Check if the custom weather place preference is enabled

            //Get the custom city, refresh the city label and get the weather
            citylbpref.setText(sharedPrefs.getString("weather_customlocation", getString(R.string.location_null)));
            getWeather1((String) citylbpref.getText());

    }

@Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub
        List<Address> addresses = null;
         if (arg0 != null){
                double longitude = arg0.getLongitude();
                double latitude = arg0.getLatitude();
                Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());

             try {
                 addresses = gcd.getFromLocation(latitude, longitude, 1);
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 Log.e("MyTag", "MyMessage", e); // use this instead e.printStackTrace();
             }

             if(addresses != null && addresses.size() > 0){
                 citylb.setText(addresses.get(0).getLocality());

                 getWeather((String) citylb.getText());
             }else{
                 citylb.setText(getString(R.string.location_null));
             }
                 //citylb = (TextView) findViewById(R.id.citybox);


                //if (addresses.size() > 0) return addresses.get(0).getLocality();
         }

    }

现在,我需要它有一个“手动”位置..我试图在这里改变“loation”:

yahooWeatherUtils.queryYahooWeather(getApplicationContext(), location, this);

使用如下字符串:

yahooWeatherUtils.queryYahooWeather(getApplicationContext(), "New York", this);

但不起作用......任何想法?

2 个答案:

答案 0 :(得分:1)

在搜索YahooWeatherUtils时,我找到了http://www.codota.com/android/scenarios/52fcbdbbda0ae4ff7532748f/com.google.android.gms.location.LocationClient?tag=dragonfly

他们的建议是:

Location location = locationClient.getLastLocation();

YahooWeatherUtils ywu = YahooWeatherUtils.getInstance();
if PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("weatherUseCurrentLocation", true) && location != null) {
   ywu.queryYahooWeather(getActivity(), location , this);
} else { 
   String city = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("weatherCity", "Vancouver Canada");
   ywu.queryYahooWeather(getActivity(), city , this);
} 

因此,似乎函数queryYahooWeather可以获得纬度/经度或城市名称。您只需要足够的城市名称信息。

答案 1 :(得分:0)

如果您使用Googleplay services,则可以在没有GPS的情况下获取您的位置信息。它似乎默认为信号塔和已知的wifi位置等来源。奖金如果设备实际上有一个GPS和gps打开谷歌播放服务将使用它但它不会烦人请打开GPS,所以这将完全适合您的应用程序。第一个修复也非常快。

public class KmlReader extends ActionBarActivity implements

         GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener, LocationListener
         {

...

    if (locationManager == null) {
                    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    locationManager.addGpsStatusListener(this);
                }




     * Called by Location Services when the request to connect the client
         * finishes successfully. At this point, you can request the current
         * location or start periodic updates
         */
        @Override
        public void onConnected(Bundle dataBundle) {
            if (action_track) {
                if (mLocationRequest == null) {
                    // Create a new global location parameters object
                    mLocationRequest = LocationRequest.create();
                    // Set the update interval
                    mLocationRequest.setInterval(UPDATE_INTERVAL);
                    // Use high accuracy
                    mLocationRequest
                            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                    // Set the interval ceiling to one minute
                    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
                }
                mLocationClient.requestLocationUpdates(mLocationRequest, this);
            } else {
                stopLocationUpdates();
            }
        }

神奇的是这个位置进入了这个方法。

@Override
public void onLocationChanged(Location location) {