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

这个案例只是为了关联各个知识点,在实际开发中还有待优化

项目结构分析:

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

WeatherManager: 用来操作Weather

MainActivity:主acaitivy

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

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

Weather:

[java] view plaincopy

  1. package com.example.weatherdemo;
  2. public class Weather
  3. {
  4. private String cityName;
  5. private String cityData;
  6. private String cityWeath;
  7. private String cityWinder;
  8. private String cityImg;
  9. public Weather(){
  10. }
  11. public Weather(String cityName,String cityData,String cityWeath,String cityWinder,String cityImg){
  12. this.cityName = cityName;
  13. this.cityData = cityData;
  14. this.cityWeath = cityWeath;
  15. this.cityWinder = cityWinder;
  16. this.cityImg = cityImg;
  17. }
  18. public String getCityName()
  19. {
  20. return cityName;
  21. }
  22. public void setCityName(String cityName)
  23. {
  24. this.cityName = cityName;
  25. }
  26. public String getCityData()
  27. {
  28. return cityData;
  29. }
  30. public void setCityData(String cityData)
  31. {
  32. this.cityData = cityData;
  33. }
  34. public String getCityWeath()
  35. {
  36. return cityWeath;
  37. }
  38. public void setCityWeath(String cityWeath)
  39. {
  40. this.cityWeath = cityWeath;
  41. }
  42. public String getCityWinder()
  43. {
  44. return cityWinder;
  45. }
  46. public void setCityWinder(String cityWinder)
  47. {
  48. this.cityWinder = cityWinder;
  49. }
  50. public String getCityImg()
  51. {
  52. return cityImg;
  53. }
  54. public void setCityImg(String cityImg)
  55. {
  56. this.cityImg = cityImg;
  57. }
  58. }

WeatherManager:

[java] view plaincopy

  1. package com.example.weatherdemo;
  2. import org.json.JSONException;
  3. import org.json.JSONObject;
  4. public class WeatherManager
  5. {
  6. Weather weather;
  7. public void setWeather(String jsonString){
  8. try
  9. {
  10. JSONObject jsonObject = new JSONObject( jsonString );
  11. JSONObject object = jsonObject.getJSONObject( "weatherinfo" );
  12. String cityName = object.getString( "city" );
  13. String cityData = object.getString( "date_y" );
  14. String cityWeath = object.getString( "weather1" );
  15. String cityWinder = object.getString( "wind1" );
  16. String cityImg = object.getString( "img1" );
  17. weather = new Weather( cityName, cityData, cityWeath, cityWinder, cityImg );
  18. }
  19. catch (JSONException e)
  20. {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24. }
  25. public Weather getWeather(){
  26. return weather;
  27. }
  28. }

CityWeatherService:

[java] view plaincopy

  1. package com.example.weatherdemo;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.InputStream;
  4. import java.net.HttpURLConnection;
  5. import java.net.MalformedURLException;
  6. import java.net.URL;
  7. import java.util.Timer;
  8. import java.util.TimerTask;
  9. import android.app.Service;
  10. import android.content.BroadcastReceiver;
  11. import android.content.Intent;
  12. import android.os.Handler;
  13. import android.os.IBinder;
  14. import android.os.Message;
  15. import android.util.Log;
  16. public class CityWeatherService extends Service
  17. {
  18. private static final int UPDATAWEATHER = 0X10;
  19. private final int GOTOBROADCAST = 0X20;
  20. public static final String BROADCASTACTION = "com.jone.broad";
  21. Timer timer;
  22. @Override
  23. public IBinder onBind(Intent arg0)
  24. {
  25. // TODO Auto-generated method stub
  26. return null;
  27. }
  28. @Override
  29. public int onStartCommand(Intent intent, int flags, int startId)
  30. {
  31. // updateWeather();
  32. timer = new Timer();
  33. timer.schedule( new TimerTask()
  34. {
  35. @Override
  36. public void run()
  37. {
  38. // 定时更新
  39. String jsonString = getWeather();
  40. // 发送广播
  41. Intent intent = new Intent();
  42. intent.setAction( BROADCASTACTION );
  43. intent.putExtra( "jsonstr", jsonString );
  44. sendBroadcast( intent );
  45. //               Message msg = handler.obtainMessage();
  46. //               msg.what = UPDATAWEATHER;
  47. //               handler.sendMessage( msg );
  48. }
  49. }, 0, 20 * 1000 );
  50. return super.onStartCommand( intent, flags, startId );
  51. }
  52. private String getWeather()
  53. {
  54. String srsString = "";
  55. try
  56. {
  57. srsString = getJsonStringGet( "http://m.weather.com.cn/data/101250101.html" );
  58. }
  59. catch (Exception e)
  60. {
  61. // TODO Auto-generated catch block
  62. e.printStackTrace();
  63. Log.i( "tag",e.getMessage() );
  64. }
  65. return srsString;
  66. }
  67. public String getJsonStringGet(String uri) throws Exception
  68. {
  69. String result = null;
  70. URL url = new URL( uri );
  71. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  72. conn.setConnectTimeout( 6 * 1000 );// 设置连接超时
  73. Log.i( "msg", conn.getResponseCode() + "???????" );
  74. if (conn.getResponseCode() == 200)
  75. {
  76. Log.i( "msg", "成功" );
  77. InputStream is = conn.getInputStream();// 得到网络返回的输入流
  78. result = readData( is, "UTF-8" );
  79. }
  80. else
  81. {
  82. Log.i( "msg", "失败" );
  83. result = "";
  84. }
  85. conn.disconnect();
  86. return result;
  87. }
  88. private String readData(InputStream inSream, String charsetName) throws Exception
  89. {
  90. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  91. byte[] buffer = new byte[1024];
  92. int len = -1;
  93. while ((len = inSream.read( buffer )) != -1)
  94. {
  95. outStream.write( buffer, 0, len );
  96. }
  97. byte[] data = outStream.toByteArray();
  98. outStream.close();
  99. inSream.close();
  100. return new String( data, charsetName );
  101. }
  102. @Override
  103. public void onDestroy()
  104. {
  105. // TODO Auto-generated method stub
  106. super.onDestroy();
  107. if(timer != null){
  108. timer.cancel();
  109. }
  110. }
  111. }

MainActivity:

[java] view plaincopy

  1. package com.example.weatherdemo;
  2. import android.os.Bundle;
  3. import android.os.Handler;
  4. import android.os.Message;
  5. import android.app.Activity;
  6. import android.content.BroadcastReceiver;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.IntentFilter;
  10. import android.view.Menu;
  11. import android.widget.TextView;
  12. public class MainActivity extends Activity
  13. {
  14. BroadcastMain  broadcastMain ;
  15. Weather weather;
  16. public static WeatherManager manager;
  17. TextView cityTextView;
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState)
  20. {
  21. super.onCreate( savedInstanceState );
  22. setContentView( R.layout.activity_main );
  23. cityTextView = (TextView) findViewById( R.id. city);
  24. manager = new WeatherManager();
  25. Intent intent = new Intent();
  26. intent.setClass(this, CityWeatherService.class);
  27. startService(intent);
  28. broadcastMain = new BroadcastMain();
  29. IntentFilter filter = new IntentFilter();
  30. filter.addAction( CityWeatherService.BROADCASTACTION );
  31. registerReceiver( broadcastMain, filter );
  32. }
  33. @Override
  34. public boolean onCreateOptionsMenu(Menu menu)
  35. {
  36. // Inflate the menu; this adds items to the action bar if it is present.
  37. getMenuInflater().inflate( R.menu.main, menu );
  38. return true;
  39. }
  40. public class BroadcastMain extends BroadcastReceiver{
  41. @Override
  42. public void onReceive(Context context, Intent intent)
  43. {
  44. //          String jsonString = intent.getExtras().getString( "jsonstr" );
  45. //          manager.setWeather( jsonString );
  46. Message msg = handler.obtainMessage();
  47. msg.what = 01;
  48. handler.sendMessage( msg );
  49. }
  50. }
  51. Handler handler = new Handler()
  52. {
  53. public void handleMessage(android.os.Message msg)
  54. {
  55. switch (msg.what)
  56. {
  57. case 01:
  58. weather = manager.getWeather();
  59. cityTextView.setText( weather.getCityName() );
  60. break;
  61. default:
  62. break;
  63. }
  64. };
  65. };
  66. @Override
  67. protected void onDestroy()
  68. {
  69. Intent intent = new Intent();
  70. intent.setClass(this, CityWeatherService.class);
  71. stopService(intent);
  72. super.onDestroy();
  73. }
  74. }

[java] view plaincopy

    1. 主要的功能实现在service中,开启一个定时器,去获取服务端的信息,通过广播来实时我们的activity中相关的组件
时间: 2024-12-26 13:40:43

android之后台定时更新ui天气【Timer、service、broadcast、activity】的相关文章

[Android Traffic] 调整定时更新的频率(C2DM与退避算法)

转载自: http://blog.csdn.net/kesenhoo/article/details/7395253 Minimizing the Effect of Regular Updates[最小化定时更新操作的副作用] 最佳的定时更新频率是不确定的,通常由设备状态,网络连接状态,用户行为与用户定义明确的偏好而决定. Optimizing Battery Life([Android Training - 04]优化电池寿命)这一章有讨论如何根据设备状态来修改更新频率.里面介绍了当断开网络

Android线程间通信更新UI的方法(重点分析EventBus)

Android的UI更新只能在UI线程中,即主线程.子线程中如果要进行UI更新,都是要通知主线程来进行. 几种实现方式总结如下,欢迎补充. 1.runOnUiThread() 子线程中持有当前Activity引用(假如为Activity mActivity;),即可以调用mActivity的runOnUiThread(Runnable r)方法. 2.post()和postDelay() 子线程如果持有某个View的引用,要对该View进行更新,则可调用该View对象的post(Runnable

android子线程中更新UI的方法

在Android项目中经常有碰到这样的问题,在子线程中完成耗时操作之后要更新UI,下面就自己经历的一些项目总结一下更新的方法: 参考:Android子线程 方法一:用Handler 1.主线程中定义Handler: Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: //

老问题:Android子线程中更新UI的3种方法

在Android项目中经常有碰到这样的问题,在子线程中完成耗时操作之后要更新UI,下面就自己经历的一些项目总结一下更新的方法: 方法一:用Handler 1.主线程中定义Handler: Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: //完成主界面更新,拿到数据 S

winform 后台线程更新UI

//后台线程更新TextBox private void SetTextBox(TextBox txt, string value) { Action act = () => { txt.Text = value; }; if (txt.InvokeRequired) { txt.Invoke(act); } else { act(); } } private void TestThread() { int i = 0; while (true) { Thread.Sleep(1000); i+

一种WPF在后台线程更新UI界面的简便方法

WPF框架规定只有UI线程(主线程)可以更新界面,所有其他后台线程无法直接更新界面.幸好,WPF提供的SynchronizationContext类以及C#的Lambda表达式提供了一种方便的解决方法.以下是代码: public static SynchronizationContext s_SC = Synchronization.Current; //主窗口类的静态成员 在App类中: static Thread s_MainThread = Thread.CurrentThread; //

Android之Handler,举例说明如何更新UI

方法一:(java习惯,在android不推荐使用) 刚刚开始接触android线程编程的时候,习惯好像java一样,试图用下面的代码解决问题 new Thread( new Runnable() { public void run() { myView.invalidate(); } }).start(); 可以实现功能,刷新UI界面.但是这样是不行的,因为它违背了单线程模型:Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行. 方法二:(Thread+Handler)

android异步更新UI的几种方法

前言 ?我们知道在android开发中不能在非ui线程中更新ui,但是,有的时候我们需要在代码中执行一些诸如访问网络.查询数据库等耗时操作,为了不阻塞ui线程,我们时常会开启一个新的线程(工作线程)来执行这些耗时操作,然后我们可能需要将查询到的数据渲染到ui组件上,那么这个时候我们就需要考虑异步更新ui的问题了. android中有下列几种异步更新ui的解决办法: Activity.runOnUiThread(Runnable) View.post(Runnable) long) View.po

Android中多线程编程(三)Handler更新UI的方式

Handler更新UI的方式和原因以及遇到的问题 1.方式: 只能通过Handler来更新UI. 代码如下: package com.chengdong.su.handlerdemo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.