Service跨进程通讯解析天气

package com.hd.weather;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


/**
 * @author HD
 * @date 2015-12-7
 * @package_name com.hd.weather
 * @file_name MainActivity.java
 */
public class MainActivity extends Activity {
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {

        };
    };

    TextView mTextView;
    private Button mButton;
    public StringBuilder sb;
    private IMyAidlInterface mInterface;
    private IWeatherCallback.Stub mCallback = new IWeatherCallback.Stub() {

        @Override
        public void showWeather(Weather weather) throws RemoteException {
            // TODO 自动生成的方法存根
            MainActivity.this.showWeather(weather);
        }

        @Override
        public void error() throws RemoteException {
            // TODO 自动生成的方法存根
            MainActivity.this.weatherErro();
        }
    };

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO 自动生成的方法存根
            try {
                mInterface.unregisterCallback(mCallback);
            } catch (RemoteException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            mInterface = null;

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO 自动生成的方法存根
            mInterface = IMyAidlInterface.Stub.asInterface(service);
            Log.i("hhhd", "connected");
            try {
                mInterface.registerCallback(mCallback);
            } catch (RemoteException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.textView);
        mButton = (Button) findViewById(R.id.button1);
        bindService();
        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO 自动生成的方法存根
                try {
                    mInterface.getWeather();
                } catch (RemoteException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }
        });
    }

    private void bindService(){
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, WeatherService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        Log.i("hhhd", "bindService");
    }

    private void unbindService(){
        unbindService(conn);
    }

    private void showWeather(Weather weather){
        Log.i("hhhd", "show Weather");
        String city = weather.getCity();
        String cityId = weather.getCityid();
        String temp = weather.getTemp();
        String WD = weather.getWD();
        String WS = weather.getWS();
        String SD = weather.getSD();
        String WSE = weather.getWSE();
        String time = weather.getTime();
        String isRadar = weather.getIsRadar();
        String Radar = weather.getRadar();
        String njd = weather.getNjd();
        String qy = weather.getQy();
        sb = new StringBuilder();
        sb.append("City:").append(city).append("\n")
        .append("CityId:").append(cityId).append("\n")
        .append("temp:").append(temp).append("\n")
        .append("WD:").append(WD).append("\n")
        .append("WS:").append(WS).append("\n")
        .append("SD:").append(SD).append("\n")
        .append("time:").append(time).append("\n")
        .append("isRadar:").append(isRadar).append("\n")
        .append("Radar:").append(Radar).append("\n")
        .append("njd:").append(njd).append("\n")
        .append("qy:").append(qy).append("\n");
        Log.i("hhhd", sb.toString());
        handler.post(new Runnable() {

            @Override
            public void run() {
                // TODO 自动生成的方法存根
                mTextView.setText(sb.toString());
            }
        });
    }

    private void weatherErro(){
        mTextView.setText("获取天气信息失败");
    }

    @Override
    protected void onDestroy() {
        // TODO 自动生成的方法存根
        super.onDestroy();
        unbindService();
    }

}
package com.hd.weather;

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

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

/**
 * @author HD
 * @date 2015-12-7
 * @package_name com.hd.weather
 * @file_name Weather.java
 */
public class Weather implements Parcelable {
    String city;
    String cityid;
    String temp;
    String WD;
    String WS;
    String SD;
    String WSE;
    String time;
    String isRadar;
    String Radar;
    String njd;
    String qy;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCityid() {
        return cityid;
    }

    public void setCityid(String cityid) {
        this.cityid = cityid;
    }

    public String getTemp() {
        return temp;
    }

    public void setTemp(String temp) {
        this.temp = temp;
    }

    public String getWD() {
        return WD;
    }

    public void setWD(String wD) {
        WD = wD;
    }

    public String getWS() {
        return WS;
    }

    public void setWS(String wS) {
        WS = wS;
    }

    public String getSD() {
        return SD;
    }

    public void setSD(String sD) {
        SD = sD;
    }

    public String getWSE() {
        return WSE;
    }

    public void setWSE(String wSE) {
        WSE = wSE;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getIsRadar() {
        return isRadar;
    }

    public void setIsRadar(String isRadar) {
        this.isRadar = isRadar;
    }

    public String getRadar() {
        return Radar;
    }

    public void setRadar(String radar) {
        Radar = radar;
    }

    public String getNjd() {
        return njd;
    }

    public void setNjd(String njd) {
        this.njd = njd;
    }

    public String getQy() {
        return qy;
    }

    public void setQy(String qy) {
        this.qy = qy;
    }

    @Override
    public int describeContents() {
        // TODO 自动生成的方法存根
        return 0;
    }

    public Weather() {
        // TODO 自动生成的构造函数存根
    }

    public Weather(Parcel in) {
        // TODO 自动生成的构造函数存根
        city = in.readString();
        cityid = in.readString();
        temp = in.readString();
        WD = in.readString();
        WS = in.readString();
        SD = in.readString();
        WSE = in.readString();
        time = in.readString();
        isRadar = in.readString();
        Radar = in.readString();
        njd = in.readString();
        qy = in.readString();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        // TODO 自动生成的方法存根
        dest.writeString(city);
        dest.writeString(cityid);
        dest.writeString(temp);
        dest.writeString(WD);
        dest.writeString(WS);
        dest.writeString(SD);
        dest.writeString(WSE);
        dest.writeString(time);
        dest.writeString(isRadar);
        dest.writeString(Radar);
        dest.writeString(njd);
        dest.writeString(qy);
    }

    public static final Parcelable.Creator<Weather> CREATOR = new Creator<Weather>() {

        @Override
        public Weather createFromParcel(Parcel source) {
            // TODO 自动生成的方法存根
            return new Weather(source);
        }

        @Override
        public Weather[] newArray(int size) {
            // TODO 自动生成的方法存根
            return new Weather[size];
        }
    };

    public static Weather jsonToWeather(JSONObject jsonObject) {
        try {
            Weather weather = new Weather();
            String city = jsonObject.getString("city");
            String cityid = jsonObject.getString("cityid");
            String temp = jsonObject.getString("temp");
            String WD = jsonObject.getString("WD");
            String WS = jsonObject.getString("WS");
            String SD = jsonObject.getString("SD");
            String WSE = jsonObject.getString("WSE");
            String time = jsonObject.getString("time");
            String isRadar = jsonObject.getString("isRadar");
            String Radar = jsonObject.getString("Radar");
            String njd = jsonObject.getString("njd");
            String qy = jsonObject.getString("qy");
            weather.setCity(city);
            weather.setCityid(cityid);
            weather.setTemp(temp);
            weather.setWD(WD);
            weather.setWS(WS);
            weather.setSD(SD);
            weather.setWSE(WSE);
            weather.setTime(time);
            weather.setIsRadar(isRadar);
            weather.setRadar(Radar);
            weather.setNjd(njd);
            weather.setQy(qy);
            return weather;
        } catch (JSONException e) {
            // TODO 自动生成的 catch 块
            Log.i("hhhd", e.toString());
        }
        return null;
    }



}
/*
 * {"weatherinfo":{"city":"北京","cityid":"101010100","temp":"9","WD":"西南风","WS":"2级"
 * ,
 * "SD":"22%","WSE":"2","time":"10:45","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB"
 * ,"njd":"暂无实况", "qy":"1014"}}
 */
package com.hd.weather;

import java.util.HashSet;
import java.util.Iterator;

import org.apache.http.protocol.ResponseConnControl;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

/**
 * @author HD
 * @date 2015-12-7
 * @package_name com.hd.weather
 * @file_name WeatherService.java
 */
public class WeatherService extends Service {
    private RequestQueue mQueue;
    private static final String URL = "http://www.weather.com.cn/adat/sk/101010100.html";
    HashSet<IWeatherCallback> mCallbacks = new HashSet<IWeatherCallback>();

    IMyAidlInterface.Stub mStub = new IMyAidlInterface.Stub() {

        @Override
        public void unregisterCallback(IWeatherCallback callback)
                throws RemoteException {
            // TODO 自动生成的方法存根
            mCallbacks.remove(callback);
        }

        @Override
        public void registerCallback(IWeatherCallback callback)
                throws RemoteException {
            // TODO 自动生成的方法存根
            mCallbacks.add(callback);
        }

        @Override
        public void getWeather() throws RemoteException {
            // TODO 自动生成的方法存根
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL,
                    null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            // TODO 自动生成的方法存根
                            try {
                                JSONObject weatherinfo = response
                                        .getJSONObject("weatherinfo");
                                Iterator<IWeatherCallback> iterator = mCallbacks
                                        .iterator();
                                Weather weather = Weather
                                        .jsonToWeather(weatherinfo);

                                while (iterator.hasNext()) {
                                    Log.i("hhhd", "iterator hasNext");
                                    iterator.next().showWeather(weather);
                                }
                            } catch (JSONException e) {
                                // TODO 自动生成的 catch 块
                                e.printStackTrace();
                            } catch (RemoteException e) {
                                // TODO 自动生成的 catch 块
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // TODO 自动生成的方法存根
                            Log.i("hhhd", "onErrorResponse");
                            Iterator<IWeatherCallback> iterator = mCallbacks
                                    .iterator();
                            while (iterator.hasNext()) {
                                try {
                                    iterator.next().error();
                                } catch (RemoteException e) {
                                    // TODO 自动生成的 catch 块
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
            mQueue.add(request);
        }

    };

    @Override
    public IBinder onBind(Intent intent) {
        // TODO 自动生成的方法存根
        return mStub;
    }

    @Override
    public void onCreate() {
        // TODO 自动生成的方法存根
        super.onCreate();
        Log.i("hhhd", "onCreate");
        mQueue = Volley.newRequestQueue(this);
    }

}

/Weather/src/com/hd/weather/IMyAidlInterface.aidl

package com.hd.weather;
import com.hd.weather.IWeatherCallback;
interface IMyAidlInterface{
    void getWeather();
    void registerCallback(IWeatherCallback callback);
    void unregisterCallback(IWeatherCallback callback);
}

/Weather/src/com/hd/weather/IWeatherCallback.aidl

package com.hd.weather;
import com.hd.weather.Weather;
//'Weather weather' can be an out parameter, so you must declare it as in, out or inout;
interface IWeatherCallback{
    void showWeather(in Weather weather);
    void error();
}

/Weather/src/com/hd/weather/Weather.aidl

package com.hd.weather;
parcelable Weather;
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.hd.weather.MainActivity" >

    <TextView 
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:gravity="center"
        android:layout_marginTop="20dp"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="36dp"
        android:text="显示厦门天气" />

</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hd.weather"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".WeatherService"
            android:process=":remote" >
        </service>
    </application>

</manifest>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值