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