activity与service通过serializable传递复杂对象

本文介绍了一种使用Android平台实现实时监控新浪微博数据更新的方法,并通过广播机制将更新后的微博数据从后台服务推送到前台应用程序的技术方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近学习新浪微博开放平台,实现了一个应用,通过后台Service监控微博数据,发现数据更新后通知前台程序,并将博客数据列表发送给前台Activity。
其中利用BroadcastReceiver对象分别在Activity和Service注册了一个广播,通过发送不同的广播控制前台和后台的数据交换,并通过Serializable对象传递复杂的自定义对象类型给Activity。

程序片段如下:后台监控weibo Service

[csharp]  view plain copy
  1. //继承自Service的子类  
  2. public class WeiboService extends Service{         
  3.         //用于判断微博是否有更新标志  
  4.         private boolean newDateFlag = false;  
  5.           
  6.         //微博对象  
  7.         Weibo weibo;  
  8.           
  9.         NotificationManager m_NotificationManager;    
  10.         Notification m_Notification;    
  11.         PendingIntent m_PendingIntent;    
  12.           
  13.         //继承自BroadcastReceiver对象,用于得到Activity发送过来的命令  
  14.     CommandReceiver cmdReceiver;  
  15.     boolean flag;  
  16.       
  17.     //Service命令列表  
  18.     int CMD_STOP_SERVICE = 0;  
  19.     int CMD_RESET_SERVICE = 1;  
  20.     int CMD_GET_WEIBO_DATA = 2;  
  21.   
  22.   @Override  
  23.     public void onCreate() {//重写onCreate方法  
  24.         flag = true;  
  25.         //初始化新浪weibo open api   
  26.         System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);  
  27.             System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);  
  28.         weibo=OAuthConstant.getInstance().getWeibo();  
  29.         //注册时,新浪给你的两个字符串,填写上去  
  30.         weibo.setToken("xxxxxx""xxxxxxxx");  
  31.           
  32.         m_Notification = new Notification();  
  33.           
  34.         super.onCreate();  
  35.           
  36.     }  
  37.       
  38.     @Override  
  39.     public IBinder onBind(Intent intent) {//重写onBind方法  
  40.         // TODO Auto-generated method stub  
  41.         return null;  
  42.     }  
  43.       
  44.    //前台Activity调用startService时,该方法自动执行  
  45.     @Override  
  46.     public int onStartCommand(Intent intent, int flags, int startId) {//重写onStartCommand方法  
  47.             cmdReceiver = new CommandReceiver();  
  48.         IntentFilter filter = new IntentFilter();//创建IntentFilter对象  
  49.         //注册一个广播,用于接收Activity传送过来的命令,控制Service的行为,如:发送数据,停止服务等  
  50.         //字符串:weibo4andriod.focusme.weiboService为自定义,没有什么要求,一般用包名+文件名,避免重复  
  51.         //如果重复,Android系统在运行期会显示一个接收相同Action的服务程序列表,供用户选择。  
  52.         //注册同一个action的程序,能否同时接收广播,待测试.....  
  53.         filter.addAction("weibo4andriod.focusme.weiboService");  
  54.         //注册Broadcast Receiver  
  55.         registerReceiver(cmdReceiver, filter);  
  56.         doJob();//调用方法启动线程  
  57.         return super.onStartCommand(intent, flags, startId);  
  58.     }  
  59.     //方法:  
  60.     public void doJob(){  
  61.         new Thread(){  
  62.             public void run(){  
  63.                       
  64.                     ArrayList<HashMap<String,String>> data;  
  65.                 while(flag){  
  66.                     try{//睡眠一段时间  
  67.                             Thread.sleep(5000);  
  68.                     }  
  69.                     catch(Exception e){  
  70.                             e.printStackTrace();  
  71.                     }  
  72.                       
  73.                     data = getWeiboData();  
  74.                       
  75.                     if(isNewDateFlag()){  
  76.                         sendNotification("xxxxxxxxx");  
  77.                           
  78.                     }   
  79.                     setNewDateFlag(false);  
  80.                 }                                  
  81.             }  
  82.         }.start();  
  83.     }   
[csharp]  view plain copy
  1.  //接收Activity传送过来的命令  
  2.     private class CommandReceiver extends BroadcastReceiver{  
  3.         @Override  
  4.         public void onReceive(Context context, Intent intent) {  
  5.             int cmd = intent.getIntExtra("cmd", -1);//获取Extra信息  
  6.                         if(cmd == CMD_STOP_SERVICE){//如果发来的消息是停止服务                                  
  7.                     flag = false;//停止线程  
  8.                     stopSelf();//停止服务  
  9.                         }        
  10.             if(cmd == CMD_RESET_SERVICE){//如果发来的消息是刷新服务                                  
  11.              
  12.             }  
  13.             if(cmd == CMD_GET_WEIBO_DATA){//如果发来的消息是发送weibo数据                                  
  14.                     sendWeiboData();  
  15.               }  
  16.         }  
  17.   
  18.                                 
  19.     }  
  20.     @Override  
  21.     public void onDestroy() {//重写onDestroy方法  
  22.         this.unregisterReceiver(cmdReceiver);//取消注册的CommandReceiver  
  23.         super.onDestroy();  
  24.     }    
  25.       
  26.    /* 
  27.      * Get Weibo data 
  28.      */  
  29.     public ArrayList<HashMap<String,String>> getWeiboData(){  
  30.               
  31.             ArrayList<HashMap<String,String>> weiboDataList   
  32.                                     = new ArrayList<HashMap<String,String>>();  
  33.               
  34.                 HashMap<String, String> map   
  35.                                         = new HashMap<String, String>();  
  36.   
  37.                 List<Status> friendsTimeline;  
  38.                   
  39.                 try {  
  40.                         friendsTimeline = weibo.getUserTimeline();  
  41.                           
  42.                         for (Status status : friendsTimeline) {  
  43.                                   
  44.                                 ofCheckNewWeibo(status.getCreatedAt());  
  45.                                   
  46.                                 map = new HashMap<String, String>();    
  47.                         map.put("CreatedAt", status.getCreatedAt().toString());    
  48.                         map.put("WeiBoText", status.getText());   
  49.                        
  50.                         weiboDataList.add(map);  
  51.   
  52.                         }          
  53.                 }  
  54.                 catch (WeiboException e) {  
  55.                         e.printStackTrace();  
  56.                 }  
  57.                 return weiboDataList;   
  58.     }  
  59.       
  60.     private void ofCheckNewWeibo(Date createdAt) {  
  61.                 // TODO Auto-generated method stub  
  62.             Date weibolastdate;  
  63.             Editor editor;  
  64.               
  65.             //通过SharedPreFerence读取和记录系统配置信息  
  66.             SharedPreferences preferences = getSharedPreferences("weiboDate",Context.MODE_PRIVATE);  
  67.           
  68.                 weibolastdate = SParseD(preferences.getString("lastDate","Mon Nov 29 16:08:43 +0800 1900"));  
  69.   
  70.                 if(weibolastdate.before(createdAt)){  
  71.                           
  72.                         editor = preferences.edit();  
  73.                    
  74.             editor.putString("lastDate", createdAt.toString());  
  75.                    
  76.             editor.commit();  
  77.                         setNewDateFlag(true);  
  78.                 }  
  79.         }  
  80.   
  81.       /** 
  82.      * 发送有微博更新的通知 
  83.      * @param sendText 
  84.      */  
  85.     public void sendNotification(String sendText){  
  86.               
  87.             Intent intent = new Intent(WeiboService.this,AndriodFocusMe.class);  
  88.           
  89.             m_Notification.icon=R.drawable.icon;   
  90.             m_Notification.tickerText=sendText;   
  91.             m_Notification.defaults=Notification.DEFAULT_SOUND;    
  92.               
  93.             m_PendingIntent=PendingIntent.getActivity(WeiboService.this, 0,intent, 0);   
  94.             m_Notification.setLatestEventInfo(WeiboService.this"title""text",m_PendingIntent);  
  95.             m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  96.             m_NotificationManager.notify(R.id.TextView01,m_Notification);    
  97.     }  
  98.       
  99.       
  100.       
  101.       
  102.     /** 
  103.      * String to Date 
  104.      * @param date 
  105.      * @return 
  106.      */  
  107.      //比较数据是否为新的  
  108.     public Date SParseD(String date){  
  109.             String format = "EEE MMM dd HH:mm:ss Z yyyy";  
  110.         SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.US);  
  111.           
  112.         Date parseDate = null;  
  113.                 try {  
  114.                         parseDate = dateFormat.parse(date);  
  115.                 } catch (ParseException e) {  
  116.                         // TODO Auto-generated catch block  
  117.                         e.printStackTrace();  
  118.                 }  
  119.           
  120.         return parseDate;  
  121.     }  
  122.       
  123.     public boolean isNewDateFlag() {  
  124.                 return newDateFlag;  
  125.         }  
  126.   
  127.         public void setNewDateFlag(boolean newDateFlag) {  
  128.                 this.newDateFlag = newDateFlag;  
  129.         }  
  130.           
  131.           
  132.         //发送微博数据列表  
  133.         public void sendWeiboData() {  
  134.                 // TODO Auto-generated method stub  
  135.                 ArrayList<HashMap<String,String>> Data;  
  136.   
  137.                 Data = getWeiboData();  
  138.                   
  139.                 Intent intent = new Intent();//创建Intent对象  
  140.           
  141.             Bundle bundle = new Bundle();  
  142.             //序列化列表,发送后在本地重建数据  
  143.             bundle.putSerializable("weibodata",Data);  
  144.             intent.setAction("weiboDataChanged");  
  145.         intent.putExtras(bundle);  
  146.         sendBroadcast(intent);//发送广播                  
  147.         }  
  148. }  
 
AndriodFocusMe 主UI界面Activity

[csharp]  view plain copy
  1. public class AndriodFocusMe extends Activity implements Runnable{  
  2.         /** Called when the activity is first created. */  
  3.     DataReceiver dataReceiver;//BroadcastReceiver对象  
  4.    
  5.       
  6.     ProgressBar progressbar;  
  7.       
  8.   
  9.     ListView listview;  
  10.       
  11.     int CMD_STOP_SERVICE = 0;  
  12.     int CMD_RESET_SERVICE = 1;  
  13.     int CMD_GET_WEIBO_DATA = 2;  
  14.       
  15.         @Override  
  16.         public void onCreate(Bundle savedInstanceState) {  
  17.                 super.onCreate(savedInstanceState);  
  18.                 setContentView(R.layout.weibodataview);  
  19.                   
  20.             Button beginOuathBtn=  (Button) findViewById(R.id.Button_WeiBo);  
  21.             Button endBtn = (Button) findViewById(R.id.flashData);  
  22.               
  23.             listview = (ListView)findViewById(R.id.weibodatalist);  
  24.   
  25.             progressbar = (ProgressBar)findViewById(R.id.wbprogressbar);  
  26.             progressbar.setVisibility(View.INVISIBLE);  
  27.   
  28.             beginOuathBtn.setOnClickListener(new Button.OnClickListener()  
  29.         {  
  30.   
  31.             @Override  
  32.             public void onClick( View v )  
  33.             {              
  34.                 Intent myIntent = new Intent(AndriodFocusMe.this, WeiboService.class);  
  35.                 AndriodFocusMe.this.startService(myIntent);//发送Intent启动Service  
  36.                 progressbar.setVisibility(View.VISIBLE);  
  37.                   
  38.                  
  39.                   
  40.   
  41.             }  
  42.         } );  
  43.               
  44.             endBtn.setOnClickListener(new Button.OnClickListener()  
  45.         {  
  46.   
  47.             @Override  
  48.             public void onClick( View v )  
  49.             {              
  50.                      Intent intent = new Intent();//创建Intent对象  
  51.                  intent.setAction("weibo4andriod.focusme.weiboService");  
  52.                  intent.putExtra("cmd", CMD_GET_WEIBO_DATA);  
  53.                  sendBroadcast(intent);//发送广播  
  54.                   
  55.   
  56.             }  
  57.         } );  
  58.       
  59.               
  60.         }  
  61.           
[csharp]  view plain copy
  1. private class DataReceiver extends BroadcastReceiver{//继承自BroadcastReceiver的子类  
  2.            
  3.          ArrayList<HashMap<String, String>> weibodatalist;  
  4.              @Override  
  5.      public void onReceive(Context context, Intent intent) {//重写onReceive方法  
  6.                        
  7.                      try {  
  8.                  Bundle bundle = intent.getExtras();  
  9.                  //反序列化,在本地重建数据  
  10.                  Serializable data = bundle.getSerializable("weibodata");  
  11.                    
  12.                  if (data != null) {  
  13.                          weibodatalist = (ArrayList<HashMap<String, String>>)data;  
  14.                                        
  15.                          SimpleAdapter mSchedule = new SimpleAdapter(AndriodFocusMe.this,weibodatalist,  
  16.                                       R.layout.weibodata_itemview,  
  17.                                       new String[] {"CreatedAt""WeiBoText"},   
  18.                                       new int[] {R.id.title,R.id.weibotext});  
  19.                    
  20.                           listview.setAdapter(mSchedule);   
  21.   
  22.                  } else {  
  23.                      return;  
  24.                  }  
  25.              } catch (Exception e) {  
  26.                  Log.v("test", e.toString());  
  27.              }  
  28.                         progressbar.setVisibility(View.GONE);  
  29.               
  30.      }                  
  31.      }  
  32.      @Override  
  33.      protected void onStart() {//重写onStart方法  
  34.                              //注册用于接收Service传送的广播  
  35.      dataReceiver = new DataReceiver();  
  36.      IntentFilter filter = new IntentFilter();//创建IntentFilter对象  
  37.      filter.addAction("weiboDataChanged");  
  38.      registerReceiver(dataReceiver, filter);//注册Broadcast Receiver  
  39.      NotificationManager m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  40.      m_NotificationManager.cancel(R.id.TextView01);  
  41.      super.onStart();  
  42.   
  43.      }  
  44.      @Override  
  45.      protected void onStop() {//重写onStop方法  
  46.      unregisterReceiver(dataReceiver);  
  47.      finish();  
  48.      super.onStop();  
  49.      }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值