您的位置:首页 > 产品设计 > UI/UE

android之后台定时更新ui天气【Timer、service、broadcast、activity】

2013-09-23 17:54 573 查看
这个案例只是为了关联各个知识点,在实际开发中还有待优化

项目结构分析:


Weather实体类:用来存放我们的天气实体

WeatherManager: 用来操作Weather

MainActivity:主acaitivy

CityWeatherService:定时轮询来更新前台的信息

原理比较简单直接贴出代码:

Weather:

package com.example.weatherdemo;

public class Weather
{

private String cityName;
private String cityData;
private String cityWeath;
private String cityWinder;
private String cityImg;

public Weather(){

}
public Weather(String cityName,String cityData,String cityWeath,String cityWinder,String cityImg){
this.cityName = cityName;
this.cityData = cityData;
this.cityWeath = cityWeath;
this.cityWinder = cityWinder;
this.cityImg = cityImg;
}

public String getCityName()
{
return cityName;
}
public void setCityName(String cityName)
{
this.cityName = cityName;
}
public String getCityData()
{
return cityData;
}
public void setCityData(String cityData)
{
this.cityData = cityData;
}
public String getCityWeath()
{
return cityWeath;
}
public void setCityWeath(String cityWeath)
{
this.cityWeath = cityWeath;
}
public String getCityWinder()
{
return cityWinder;
}
public void setCityWinder(String cityWinder)
{
this.cityWinder = cityWinder;
}
public String getCityImg()
{
return cityImg;
}
public void setCityImg(String cityImg)
{
this.cityImg = cityImg;
}

}

WeatherManager:

package com.example.weatherdemo;

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

public class WeatherManager
{

Weather weather;

public void setWeather(String jsonString){
try
{
JSONObject jsonObject = new JSONObject( jsonString );
JSONObject object = jsonObject.getJSONObject( "weatherinfo" );
String cityName = object.getString( "city" );
String cityData = object.getString( "date_y" );
String cityWeath = object.getString( "weather1" );
String cityWinder = object.getString( "wind1" );
String cityImg = object.getString( "img1" );
weather = new Weather( cityName, cityData, cityWeath, cityWinder, cityImg );
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public Weather getWeather(){
return weather;
}

}


CityWeatherService:

package com.example.weatherdemo;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class CityWeatherService extends Service
{
private static final int UPDATAWEATHER = 0X10;

private final int GOTOBROADCAST = 0X20;

public static final String BROADCASTACTION = "com.jone.broad";

Timer timer;

@Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{

// updateWeather();
timer = new Timer();
timer.schedule( new TimerTask()
{

@Override
public void run()
{
// 定时更新
String jsonString = getWeather();
// 发送广播
Intent intent = new Intent();
intent.setAction( BROADCASTACTION );
intent.putExtra( "jsonstr", jsonString );
sendBroadcast( intent );
//				 Message msg = handler.obtainMessage();
//				 msg.what = UPDATAWEATHER;
//				 handler.sendMessage( msg );

}
}, 0, 20 * 1000 );

return super.onStartCommand( intent, flags, startId );
}

private String getWeather()
{

String srsString = "";
try
{
srsString = getJsonStringGet( "http://m.weather.com.cn/data/101250101.html" );
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
Log.i( "tag",e.getMessage() );
}

return srsString;
}

public String getJsonStringGet(String uri) throws Exception
{
String result = null;
URL url = new URL( uri );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout( 6 * 1000 );// 设置连接超时
Log.i( "msg", conn.getResponseCode() + "???????" );
if (conn.getResponseCode() == 200)
{
Log.i( "msg", "成功" );
InputStream is = conn.getInputStream();// 得到网络返回的输入流
result = readData( is, "UTF-8" );
}
else
{
Log.i( "msg", "失败" );
result = "";
}
conn.disconnect();
return result;

}

private String readData(InputStream inSream, String charsetName) throws Exception
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inSream.read( buffer )) != -1)
{
outStream.write( buffer, 0, len );
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String( data, charsetName );
}

@Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
if(timer != null){
timer.cancel();
}
}

}


MainActivity:

package com.example.weatherdemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity
{

BroadcastMain  broadcastMain ;
Weather weather;
public static WeatherManager manager;

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

cityTextView = (TextView) findViewById( R.id. city);
manager = new WeatherManager();
Intent intent = new Intent();
intent.setClass(this, CityWeatherService.class);
startService(intent);
broadcastMain = new BroadcastMain();
IntentFilter filter = new IntentFilter();
filter.addAction( CityWeatherService.BROADCASTACTION );
registerReceiver( broadcastMain, filter );

}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate( R.menu.main, menu );
return true;
}

public class BroadcastMain extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent)
{
//			String jsonString = intent.getExtras().getString( "jsonstr" );
//			manager.setWeather( jsonString );
Message msg = handler.obtainMessage();
msg.what = 01;
handler.sendMessage( msg );
}
}

Handler handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case 01:
weather = manager.getWeather();
cityTextView.setText( weather.getCityName() );
break;

default:
break;
}

};

};
@Override
protected void onDestroy()
{

Intent intent = new Intent();
intent.setClass(this, CityWeatherService.class);
stopService(intent);
super.onDestroy();
}

}

主要的功能实现在service中,开启一个定时器,去获取服务端的信息,通过广播来实时我们的activity中相关的组件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐