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

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

[1].[代码] AndriodFocusMe 主UI界面Activity 跳至 [1] [2]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
public class AndriodFocusMe extends Activity implements Runnable{
         /** Called when the activity is first created. */
     DataReceiver dataReceiver; //BroadcastReceiver对象
 
    
     ProgressBar progressbar;
    
 
     ListView listview;
    
     int CMD_STOP_SERVICE = 0 ;
     int CMD_RESET_SERVICE = 1 ;
     int CMD_GET_WEIBO_DATA = 2 ;
    
         @Override
         public void onCreate(Bundle savedInstanceState) {
                 super .onCreate(savedInstanceState);
                 setContentView(R.layout.weibodataview);
                
             Button beginOuathBtn=  (Button) findViewById(R.id.Button_WeiBo);
             Button endBtn = (Button) findViewById(R.id.flashData);
             
             listview = (ListView)findViewById(R.id.weibodatalist);
 
             progressbar = (ProgressBar)findViewById(R.id.wbprogressbar);
             progressbar.setVisibility(View.INVISIBLE);
 
             beginOuathBtn.setOnClickListener( new Button.OnClickListener()
         {
 
             @Override
             public void onClick( View v )
             {           
                 Intent myIntent = new Intent(AndriodFocusMe. this , WeiboService. class );
                 AndriodFocusMe. this .startService(myIntent); //发送Intent启动Service
                 progressbar.setVisibility(View.VISIBLE);
                
                
                
 
             }
         } );
             
             endBtn.setOnClickListener( new Button.OnClickListener()
         {
 
             @Override
             public void onClick( View v )
             {           
                      Intent intent = new Intent(); //创建Intent对象
                  intent.setAction( "weibo4andriod.focusme.weiboService" );
                  intent.putExtra( "cmd" , CMD_GET_WEIBO_DATA);
                  sendBroadcast(intent); //发送广播
                
 
             }
         } );
    
             
         }
         
     private class DataReceiver extends BroadcastReceiver{ //继承自BroadcastReceiver的子类
             
             ArrayList<HashMap<String, String>> weibodatalist;
                 @Override
         public void onReceive(Context context, Intent intent) { //重写onReceive方法
                         
                         try {
                     Bundle bundle = intent.getExtras();
                     //反序列化,在本地重建数据
                     Serializable data = bundle.getSerializable( "weibodata" );
                     
                     if (data != null ) {
                             weibodatalist = (ArrayList<HashMap<String, String>>)data;
                                        
                             SimpleAdapter mSchedule = new SimpleAdapter(AndriodFocusMe. this ,weibodatalist,
                                          R.layout.weibodata_itemview,
                                          new String[] { "CreatedAt" , "WeiBoText" },
                                          new int [] {R.id.title,R.id.weibotext});
                     
                              listview.setAdapter(mSchedule);
 
                     } else {
                         return ;
                     }
                 } catch (Exception e) {
                     Log.v( "test" , e.toString());
                 }
                            progressbar.setVisibility(View.GONE);
                
         }              
         }
         @Override
         protected void onStart() { //重写onStart方法
                                 //注册用于接收Service传送的广播
         dataReceiver = new DataReceiver();
         IntentFilter filter = new IntentFilter(); //创建IntentFilter对象
         filter.addAction( "weiboDataChanged" );
         registerReceiver(dataReceiver, filter); //注册Broadcast Receiver
         NotificationManager m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
         m_NotificationManager.cancel(R.id.TextView01);
         super .onStart();
 
         }
         @Override
         protected void onStop() { //重写onStop方法
         unregisterReceiver(dataReceiver);
         finish();
         super .onStop();
         }
 
}

[2].[代码] [Java]代码 跳至 [1] [2]

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值