com.mobilevangelist.glass.helloworld.GetTheWeatherActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.mobilevangelist.glass.helloworld.GetTheWeatherActivity.java

Source

/*
 * Copyright (C) 2013 Mobilevangelist.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.mobilevangelist.glass.helloworld;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.Image;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.glass.media.Sounds;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Main activity.
 */
public class GetTheWeatherActivity extends Activity {

    private TextView _mainTextView;
    private ImageView _weatherIconImageView;

    private TextToSpeech _speech;

    private Context _context = this;
    private double mTemp;
    private String mCurrent; //String of current temp
    private String mDescription;
    private String spokenText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ArrayList<String> voiceResults = getIntent().getExtras().getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
        if (voiceResults != null && voiceResults.size() > 0) {
            spokenText = voiceResults.get(0);
        }

        Log.i("TEST: ", spokenText);

        _speech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                //          _speech.speak("The weather is" + mCurrent + "Fahrenheit and" + mDescription, TextToSpeech.QUEUE_FLUSH, null);
            }
        });

        setContentView(R.layout.layout_get_the_weather);
        _weatherIconImageView = (ImageView) findViewById(R.id.weatherIconImageView);
        _mainTextView = (TextView) findViewById(R.id.main_text_view);
        new FetchWeather().execute();
    }

    /**
     * Handle the tap event from the touchpad.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
        // Handle tap events.
        case KeyEvent.KEYCODE_DPAD_CENTER:
            //case KeyEvent.KEYCODE_ENTER:

            AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            audio.playSoundEffect(Sounds.TAP);

            _speech.speak("The weather is" + mCurrent + "Fahrenheit and" + mDescription, TextToSpeech.QUEUE_FLUSH,
                    null);

            Bitmap bitmap = loadImageFromURL("http://openweathermap.org/img/w/10d.png");
            _weatherIconImageView.setImageBitmap(bitmap);

            return true;
        default:
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        _speech.speak("Goodbye", TextToSpeech.QUEUE_FLUSH, null);

        super.onDestroy();
    }

    private class FetchWeather extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            Location loc = getLastLocation(getApplicationContext());

            return new weatherFinder().getWeather(spokenText);
            //            return new weatherFinder(loc).getWeather();
        }

        @Override
        protected void onPostExecute(String str) {

            try {

                JSONObject weatherObject = new JSONObject(str);
                JSONObject temp = weatherObject.getJSONObject("main");
                double currentTemp = temp.getDouble("temp");
                mTemp = (currentTemp - 273.15) * 1.800 + 32.00;
                mCurrent = Double.toString(Math.round(mTemp)) + (char) 0x00B0;

                JSONArray d = weatherObject.getJSONArray("weather");
                JSONObject desc = d.getJSONObject(0);
                mDescription = desc.getString("description");

                Log.i("Weatherobject: ", temp.toString());

                _mainTextView.setText(mCurrent + " and " + mDescription);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    public static Location getLastLocation(Context context) {
        Location result = null;
        LocationManager locationManager;
        Criteria locationCriteria;
        List<String> providers;

        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        locationCriteria = new Criteria();
        locationCriteria.setAccuracy(Criteria.NO_REQUIREMENT);
        providers = locationManager.getProviders(locationCriteria, true);

        // Note that providers = locatoinManager.getAllProviders(); is not used because the
        // list might contain disabled providers or providers that are not allowed to be called.

        //Note that getAccuracy can return 0, indicating that there is no known accuracy.

        for (String provider : providers) {
            Location location = locationManager.getLastKnownLocation(provider);
            if (result == null) {
                result = location;
            } else if (result.getAccuracy() == 0.0) {
                if (location.getAccuracy() != 0.0) {
                    result = location;
                    break;
                } else {
                    if (result.getAccuracy() > location.getAccuracy()) {
                        result = location;
                    }
                }
            }
        }

        return result;
    }

    private Drawable loadImageFromWeb(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src");
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }

    }

    private Bitmap loadImageFromURL(String getURL) {

        try {
            URL url = new URL(getURL);

            HttpGet httpRequest = null;
            httpRequest = new HttpGet(url.toURI());
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
            HttpEntity entity = response.getEntity();
            BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
            InputStream input = b_entity.getContent();
            Bitmap bitmap = BitmapFactory.decodeStream(input);
            return bitmap;
        } catch (Exception ex) {

            Toast t2 = Toast.makeText(getApplicationContext(), "Image Loading Failed", Toast.LENGTH_LONG);
            t2.setGravity(Gravity.CENTER, 0, 0);
            t2.show();
            return null;
        }
    }

}