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


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

     项目结构分析:

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

    WeatherManager: 用来操作Weather

    MainActivity:主acaitivy

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

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

    Weather:

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

    WeatherManager:

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


    CityWeatherService:

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


    MainActivity:

    [java] view plaincopy
     
    1. package com.example.weatherdemo;  
    2.   
    3. import android.os.Bundle;  
    4. import android.os.Handler;  
    5. import android.os.Message;  
    6. import android.app.Activity;  
    7. import android.content.BroadcastReceiver;  
    8. import android.content.Context;  
    9. import android.content.Intent;  
    10. import android.content.IntentFilter;  
    11. import android.view.Menu;  
    12. import android.widget.TextView;  
    13.   
    14. public class MainActivity extends Activity  
    15. {  
    16.   
    17.     BroadcastMain  broadcastMain ;  
    18.     Weather weather;  
    19.     public static WeatherManager manager;  
    20.       
    21.     TextView cityTextView;  
    22.     @Override  
    23.     protected void onCreate(Bundle savedInstanceState)  
    24.     {  
    25.         super.onCreate( savedInstanceState );  
    26.         setContentView( R.layout.activity_main );  
    27.           
    28.         cityTextView = (TextView) findViewById( R.id. city);  
    29.         manager = new WeatherManager();  
    30.         Intent intent = new Intent();  
    31.         intent.setClass(this, CityWeatherService.class);  
    32.         startService(intent);  
    33.         broadcastMain = new BroadcastMain();  
    34.         IntentFilter filter = new IntentFilter();  
    35.         filter.addAction( CityWeatherService.BROADCASTACTION );  
    36.         registerReceiver( broadcastMain, filter );  
    37.           
    38.     }  
    39.   
    40.   
    41.     @Override  
    42.     public boolean onCreateOptionsMenu(Menu menu)  
    43.     {  
    44.         // Inflate the menu; this adds items to the action bar if it is present.  
    45.         getMenuInflater().inflate( R.menu.main, menu );  
    46.         return true;  
    47.     }  
    48.   
    49.     public class BroadcastMain extends BroadcastReceiver{  
    50.         @Override  
    51.         public void onReceive(Context context, Intent intent)  
    52.         {  
    53. //          String jsonString = intent.getExtras().getString( "jsonstr" );  
    54. //          manager.setWeather( jsonString );  
    55.             Message msg = handler.obtainMessage();  
    56.             msg.what = 01;  
    57.             handler.sendMessage( msg );  
    58.         }  
    59.     }  
    60.       
    61.       
    62.       
    63.     Handler handler = new Handler()  
    64.     {  
    65.         public void handleMessage(android.os.Message msg)  
    66.         {  
    67.             switch (msg.what)  
    68.             {  
    69.                 case 01:  
    70.                     weather = manager.getWeather();  
    71.                     cityTextView.setText( weather.getCityName() );  
    72.                     break;  
    73.   
    74.                 default:  
    75.                     break;  
    76.             }  
    77.               
    78.         };  
    79.   
    80.     };  
    81.     @Override  
    82.     protected void onDestroy()  
    83.     {  
    84.   
    85.         Intent intent = new Intent();  
    86.         intent.setClass(this, CityWeatherService.class);  
    87.         stopService(intent);  
    88.         super.onDestroy();  
    89.     }  
    90.       
    91.       
    92. }  
    [java] view plaincopy
     
      1. 主要的功能实现在service中,开启一个定时器,去获取服务端的信息,通过广播来实时我们的activity中相关的组件  
  • 相关阅读:
    05,WP8的文件和存储
    04,WP8的async和await
    01,Windows Phone 8 介绍
    开源工作流引擎
     RMS集成的时候会出这样那样的问题
    ASP.NET第一次访问慢的完美解决方案(MVC,Web Api)
    SharePoint2010关闭我的网站(个人网站)
    SMSServer的网关配置
    文件间调用变量(extern,include)[转]
    [转]安装SMSServer作为Windows系统服务
  • 原文地址:https://www.cnblogs.com/lingyi1111/p/4531621.html
Copyright © 2020-2023  润新知