Activity与Service通过广播交换复杂对象数据用法详解

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


AndriodFocusMe 主UI界面Activity
  1. public class AndriodFocusMe extends Activity implements Runnable{
  2.         /** Called when the activity is first created. */
  3.     DataReceiver dataReceiver;//BroadcastReceiver对象

  4.     
  5.     ProgressBar progressbar;
  6.     

  7.     ListView listview;
  8.     
  9.     int CMD_STOP_SERVICE = 0;
  10.     int CMD_RESET_SERVICE = 1;
  11.     int CMD_GET_WEIBO_DATA = 2;
  12.     
  13.         @Override
  14.         public void onCreate(Bundle savedInstanceState) {
  15.                 super.onCreate(savedInstanceState);
  16.                 setContentView(R.layout.weibodataview);
  17.                 
  18.             Button beginOuathBtn=  (Button) findViewById(R.id.Button_WeiBo);
  19.             Button endBtn = (Button) findViewById(R.id.flashData);
  20.             
  21.             listview = (ListView)findViewById(R.id.weibodatalist);

  22.             progressbar = (ProgressBar)findViewById(R.id.wbprogressbar);
  23.             progressbar.setVisibility(View.INVISIBLE);

  24.             beginOuathBtn.setOnClickListener(new Button.OnClickListener()
  25.         {

  26.             @Override
  27.             public void onClick( View v )
  28.             {            
  29.                 Intent myIntent = new Intent(AndriodFocusMe.this, WeiboService.class);
  30.                 AndriodFocusMe.this.startService(myIntent);//发送Intent启动Service
  31.                 progressbar.setVisibility(View.VISIBLE);
  32.                 
  33.                
  34.                 

  35.             }
  36.         } );
  37.             
  38.             endBtn.setOnClickListener(new Button.OnClickListener()
  39.         {

  40.             @Override
  41.             public void onClick( View v )
  42.             {            
  43.                      Intent intent = new Intent();//创建Intent对象
  44.                  intent.setAction("weibo4andriod.focusme.weiboService");
  45.                  intent.putExtra("cmd", CMD_GET_WEIBO_DATA);
  46.                  sendBroadcast(intent);//发送广播
  47.                 

  48.             }
  49.         } );
  50.     
  51.             
  52.         }
  53.         
  54.     private class DataReceiver extends BroadcastReceiver{//继承自BroadcastReceiver的子类
  55.             
  56.             ArrayList<HashMap<String, String>> weibodatalist;
  57.                 @Override
  58.         public void onReceive(Context context, Intent intent) {//重写onReceive方法
  59.                         
  60.                         try {
  61.                     Bundle bundle = intent.getExtras();
  62.                     //反序列化,在本地重建数据
  63.                     Serializable data = bundle.getSerializable("weibodata");
  64.                     
  65.                     if (data != null) {
  66.                             weibodatalist = (ArrayList<HashMap<String, String>>)data;
  67.                                         
  68.                             SimpleAdapter mSchedule = new SimpleAdapter(AndriodFocusMe.this,weibodatalist,
  69.                                          R.layout.weibodata_itemview,
  70.                                          new String[] {"CreatedAt", "WeiBoText"}, 
  71.                                          new int[] {R.id.title,R.id.weibotext});
  72.                     
  73.                              listview.setAdapter(mSchedule); 

  74.                     } else {
  75.                         return;
  76.                     }
  77.                 } catch (Exception e) {
  78.                     Log.v("test", e.toString());
  79.                 }
  80.                            progressbar.setVisibility(View.GONE);
  81.                
  82.         }                
  83.         }
  84.         @Override
  85.         protected void onStart() {//重写onStart方法
  86.                                 //注册用于接收Service传送的广播
  87.         dataReceiver = new DataReceiver();
  88.         IntentFilter filter = new IntentFilter();//创建IntentFilter对象
  89.         filter.addAction("weiboDataChanged");
  90.         registerReceiver(dataReceiver, filter);//注册Broadcast Receiver
  91.         NotificationManager m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  92.         m_NotificationManager.cancel(R.id.TextView01);
  93.         super.onStart();

  94.         }
  95.         @Override
  96.         protected void onStop() {//重写onStop方法
  97.         unregisterReceiver(dataReceiver);
  98.         finish();
  99.         super.onStop();
  100.         }

  101. }
复制代码

通过这个例子,基本可以掌握Android常用组件的用法,希望能给各位读者带来帮助,并欢迎提出宝贵意见。

 
   

Rank: 4

UID
4914
精华
0
帖子
106
e望
1 点
e币
418 元
2#
  发表于 2011-5-31 13:53:53  | 只看该作者
  1. //继承自Service的子类
  2. public class WeiboService extends Service{
  3.         
  4.         
  5.         //用于判断微博是否有更新标志
  6.         private boolean newDateFlag = false;
  7.         
  8.         //微博对象
  9.         Weibo weibo;
  10.         
  11.         NotificationManager m_NotificationManager;  
  12.         Notification m_Notification;  
  13.         PendingIntent m_PendingIntent;  
  14.         
  15.         //继承自BroadcastReceiver对象,用于得到Activity发送过来的命令
  16.     CommandReceiver cmdReceiver;
  17.     boolean flag;
  18.     
  19.     //Service命令列表
  20.     int CMD_STOP_SERVICE = 0;
  21.     int CMD_RESET_SERVICE = 1;
  22.     int CMD_GET_WEIBO_DATA = 2;

  23.     @Override
  24.     public void onCreate() {//重写onCreate方法
  25.         flag = true;
  26.         //初始化新浪weibo open api 
  27.         System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
  28.             System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
  29.         weibo=OAuthConstant.getInstance().getWeibo();
  30.         //注册时,新浪给你的两个字符串,填写上去
  31.         weibo.setToken("xxxxxx", "xxxxxxxx");
  32.         
  33.         m_Notification = new Notification();
  34.         
  35.         super.onCreate();
  36.         
  37.     }
  38.     
  39.     @Override
  40.     public IBinder onBind(Intent intent) {//重写onBind方法
  41.         // TODO Auto-generated method stub
  42.         return null;
  43.     }
  44.     
  45.     //前台Activity调用startService时,该方法自动执行
  46.     @Override
  47.     public int onStartCommand(Intent intent, int flags, int startId) {//重写onStartCommand方法
  48.             cmdReceiver = new CommandReceiver();
  49.         IntentFilter filter = new IntentFilter();//创建IntentFilter对象
  50.         //注册一个广播,用于接收Activity传送过来的命令,控制Service的行为,如:发送数据,停止服务等
  51.         //字符串:weibo4andriod.focusme.weiboService为自定义,没有什么要求,一般用包名+文件名,避免重复
  52.         //如果重复,Android系统在运行期会显示一个接收相同Action的服务程序列表,供用户选择。
  53.         //注册同一个action的程序,能否同时接收广播,待测试.....
  54.         filter.addAction("weibo4andriod.focusme.weiboService");
  55.         //注册Broadcast Receiver
  56.         registerReceiver(cmdReceiver, filter);
  57.         doJob();//调用方法启动线程
  58.         return super.onStartCommand(intent, flags, startId);
  59.     }
  60.     //方法:
  61.     public void doJob(){
  62.         new Thread(){
  63.             public void run(){
  64.                     
  65.                     ArrayList<HashMap<String,String>> data;
  66.                 while(flag){
  67.                     try{//睡眠一段时间
  68.                             Thread.sleep(5000);
  69.                     }
  70.                     catch(Exception e){
  71.                             e.printStackTrace();
  72.                     }
  73.                     
  74.                     data = getWeiboData();
  75.                     
  76.                     if(isNewDateFlag()){
  77.                         sendNotification("xxxxxxxxx");
  78.                         
  79.                     } 
  80.                     setNewDateFlag(false);
  81.                 }                                
  82.             }
  83.         }.start();
  84.     } 
  85.     //接收Activity传送过来的命令
  86.     private class CommandReceiver extends BroadcastReceiver{
  87.         @Override
  88.         public void onReceive(Context context, Intent intent) {
  89.             int cmd = intent.getIntExtra("cmd", -1);//获取Extra信息
  90.                         if(cmd == CMD_STOP_SERVICE){//如果发来的消息是停止服务                                
  91.                     flag = false;//停止线程
  92.                     stopSelf();//停止服务
  93.                         }      
  94.             if(cmd == CMD_RESET_SERVICE){//如果发来的消息是刷新服务                                
  95.            
  96.             }
  97.             if(cmd == CMD_GET_WEIBO_DATA){//如果发来的消息是发送weibo数据                                
  98.                     sendWeiboData();
  99.               }
  100.         }

  101.                               
  102.     }
  103.     @Override
  104.     public void onDestroy() {//重写onDestroy方法
  105.         this.unregisterReceiver(cmdReceiver);//取消注册的CommandReceiver
  106.         super.onDestroy();
  107.     }  
  108.     
  109.     /*
  110.      * Get Weibo data
  111.      */
  112.     public ArrayList<HashMap<String,String>> getWeiboData(){
  113.             
  114.             ArrayList<HashMap<String,String>> weiboDataList 
  115.                                     = new ArrayList<HashMap<String,String>>();
  116.             
  117.                 HashMap<String, String> map 
  118.                                         = new HashMap<String, String>();

  119.                 List<Status> friendsTimeline;
  120.                 
  121.                 try {
  122.                         friendsTimeline = weibo.getUserTimeline();
  123.                         
  124.                         for (Status status : friendsTimeline) {
  125.                                 
  126.                                 ofCheckNewWeibo(status.getCreatedAt());
  127.                                 
  128.                                 map = new HashMap<String, String>();  
  129.                         map.put("CreatedAt", status.getCreatedAt().toString());  
  130.                         map.put("WeiBoText", status.getText()); 
  131.                      
  132.                         weiboDataList.add(map);

  133.                         }        
  134.                 }
  135.                 catch (WeiboException e) {
  136.                         e.printStackTrace();
  137.                 }
  138.                 return weiboDataList; 
  139.     }
  140.     
  141.     private void ofCheckNewWeibo(Date createdAt) {
  142.                 // TODO Auto-generated method stub
  143.             Date weibolastdate;
  144.             Editor editor;
  145.             
  146.             //通过SharedPreFerence读取和记录系统配置信息
  147.             SharedPreferences preferences = getSharedPreferences("weiboDate",Context.MODE_PRIVATE);
  148.         
  149.                 weibolastdate = SParseD(preferences.getString("lastDate","Mon Nov 29 16:08:43 +0800 1900"));

  150.                 if(weibolastdate.before(createdAt)){
  151.                         
  152.                         editor = preferences.edit();
  153.                  
  154.             editor.putString("lastDate", createdAt.toString());
  155.                  
  156.             editor.commit();
  157.                         setNewDateFlag(true);
  158.                 }
  159.         }

  160.         /**
  161.      * 发送有微博更新的通知
  162.      * @param sendText
  163.      */
  164.     public void sendNotification(String sendText){
  165.             
  166.             Intent intent = new Intent(WeiboService.this,AndriodFocusMe.class);
  167.         
  168.             m_Notification.icon=R.drawable.icon; 
  169.             m_Notification.tickerText=sendText; 
  170.             m_Notification.defaults=Notification.DEFAULT_SOUND;  
  171.             
  172.             m_PendingIntent=PendingIntent.getActivity(WeiboService.this, 0,intent, 0); 
  173.             m_Notification.setLatestEventInfo(WeiboService.this, "title", "text",m_PendingIntent);
  174.             m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  175.             m_NotificationManager.notify(R.id.TextView01,m_Notification);  
  176.     }
  177.     
  178.     
  179.     
  180.     
  181.     /**
  182.      * String to Date
  183.      * @param date
  184.      * @return
  185.      */
  186.      //比较数据是否为新的
  187.     public Date SParseD(String date){
  188.             String format = "EEE MMM dd HH:mm:ss Z yyyy";
  189.         SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.US);
  190.         
  191.         Date parseDate = null;
  192.                 try {
  193.                         parseDate = dateFormat.parse(date);
  194.                 } catch (ParseException e) {
  195.                         // TODO Auto-generated catch block
  196.                         e.printStackTrace();
  197.                 }
  198.         
  199.         return parseDate;
  200.     }
  201.     
  202.     public boolean isNewDateFlag() {
  203.                 return newDateFlag;
  204.         }

  205.         public void setNewDateFlag(boolean newDateFlag) {
  206.                 this.newDateFlag = newDateFlag;
  207.         }
  208.         
  209.         
  210.         //发送微博数据列表
  211.         public void sendWeiboData() {
  212.                 // TODO Auto-generated method stub
  213.                 ArrayList<HashMap<String,String>> Data;

  214.                 Data = getWeiboData();
  215.                 
  216.                 Intent intent = new Intent();//创建Intent对象
  217.         
  218.             Bundle bundle = new Bundle();
  219.             //序列化列表,发送后在本地重建数据
  220.             bundle.putSerializable("weibodata",Data);
  221.             intent.setAction("weiboDataChanged");
  222.         intent.putExtras(bundle);
  223.         sendBroadcast(intent);//发送广播                
  224.         }
  225. }
复制代码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
04-26
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值