MyWeatherService.java Source code

Java tutorial

Introduction

Here is the source code for MyWeatherService.java

Source

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.Toast;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyWeatherService extends Service {

    Messenger messengerToClient = null;

    MyIncomingHandler myIncomingHandler = new MyIncomingHandler();
    Messenger messengerToService = new Messenger(myIncomingHandler);

    @Override
    public IBinder onBind(Intent intent) {
        doToast(R.string.service_bound);
        return messengerToService.getBinder();
    }

    class MyIncomingHandler extends Handler {

        @Override
        public void handleMessage(Message incomingMessage) {
            messengerToClient = incomingMessage.replyTo;
            new MyAsyncTask().execute(incomingMessage.getData().getString("location"));
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        doToast(R.string.service_stopped_itself);
        stopSelf();
        return false;
    }

    @Override
    public void onDestroy() {
        myIncomingHandler = null;
        doToast(R.string.service_destroyed);
    }

    void doToast(int resource) {
        Toast.makeText(this, resource, Toast.LENGTH_SHORT).show();
    }

    class MyAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... locations) {
            return getWeatherFromInternet(locations[0]);
        }

        @Override
        protected void onPostExecute(String actualWeatherString) {
            sendWeatherToClient(actualWeatherString);
            doToast(R.string.message_handled);
        }

    }

    private static final String WEATHER_UNDERGROUND_URL = "http://api.wunderground.com/"
            + "api/your_key_id/conditions/q/";
    private static final String CONDITION = "weather";
    private static final String TEMP_F = "temp_f";

    String getWeatherFromInternet(String location) {
        String temperature = "", condition = "", weatherString;

        URL url;

        if (location != null && !location.equals("")) {
            try {
                url = new URL(WEATHER_UNDERGROUND_URL + location + ".json");

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();

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

                String oneLineFromInternet;
                String wholeReplyFromInternet = "";
                while ((oneLineFromInternet = reader.readLine()) != null) {
                    wholeReplyFromInternet += oneLineFromInternet + " ";
                }

                JSONObject jsonObject = new JSONObject(wholeReplyFromInternet);
                JSONObject current_observation = jsonObject.getJSONObject("current_observation");
                temperature = current_observation.getString(TEMP_F);
                condition = current_observation.getString(CONDITION);

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

            weatherString = temperature + (char) 0x00B0 + "F " + condition;
        } else {
            weatherString = "It's dark at night.";
        }
        return weatherString;
    }

    void sendWeatherToClient(String actualWeatherString) {
        Bundle reply = new Bundle();
        reply.putString("weather", actualWeatherString);
        Message replyMessage = Message.obtain();
        replyMessage.setData(reply);
        try {
            messengerToClient.send(replyMessage);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

}