您的位置:首页 > 其它

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

2011-12-03 12:03 387 查看
最近学习新浪微博开放平台,实现了一个应用,通过后台Service监控微博数据,发现数据更新后通知前台程序,并将博客数据列表发送给前台Activity。

其中利用BroadcastReceiver对象分别在Activity和Service注册了一个广播,通过发送不同的广播控制前台和后台的数据交换,并通过Serializable对象传递复杂的自定义对象类型给Activity。

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

//继承自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);//发送广播
}
}


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();
}

}


通过这个例子,基本可以掌握Android常用组件的用法,希望能给各位读者带来帮助,并欢迎提出宝贵意见。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: