展会信息港展会大全

Activity与Service通过广播交换复杂对象数据用法
来源:互联网   发布日期:2016-01-14 10:12:31   浏览:1899次  

导读:最近学习新浪微博开放平台,实现了一个应用,通过后台Service监控微博数据,发现数据更新后通知前台程序,并将博客数据列表发送给前台Activity。其中利用BroadcastReceiver对象分别在Activity和Service注册了一个......

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

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

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

[代码] AndriodFocusMe 主UI界面Activity

001

public class AndriodFocusMe extends Activity implements Runnable{

002

/** Called when the activity is first created. */

003

DataReceiver dataReceiver;//BroadcastReceiver对象

004

005

006

ProgressBar progressbar;

007

008

009

ListView listview;

010

011

int CMD_STOP_SERVICE = 0;

012

int CMD_RESET_SERVICE = 1;

013

int CMD_GET_WEIBO_DATA = 2;

014

015

@Override

016

public void onCreate(Bundle savedInstanceState) {

017

super.onCreate(savedInstanceState);

018

setContentView(R.layout.weibodataview);

019

020

Button beginOuathBtn=(Button) findViewById(R.id.Button_WeiBo);

021

Button endBtn = (Button) findViewById(R.id.flashData);

022

023

listview = (ListView)findViewById(R.id.weibodatalist);

024

025

progressbar = (ProgressBar)findViewById(R.id.wbprogressbar);

026

progressbar.setVisibility(View.INVISIBLE);

027

028

beginOuathBtn.setOnClickListener(new Button.OnClickListener()

029

{

030

031

@Override

032

public void onClick( View v )

033

{

034

Intent myIntent = new Intent(AndriodFocusMe.this, WeiboService.class);

035

AndriodFocusMe.this.startService(myIntent);//发送Intent启动Service

036

progressbar.setVisibility(View.VISIBLE);

037

038

039

040

041

}

042

} );

043

044

endBtn.setOnClickListener(new Button.OnClickListener()

045

{

046

047

@Override

048

public void onClick( View v )

049

{

050

Intent intent = new Intent();//创建Intent对象

051

intent.setAction("weibo4andriod.focusme.weiboService");

052

intent.putExtra("cmd", CMD_GET_WEIBO_DATA);

053

sendBroadcast(intent);//发送广播

054

055

056

}

057

} );

058

059

060

}

061

062

private class DataReceiver extends BroadcastReceiver{//继承自BroadcastReceiver的子类

063

064

ArrayList<HashMap<String, String>> weibodatalist;

065

@Override

066

public void onReceive(Context context, Intent intent) {//重写onReceive方法

067

068

try {

069

Bundle bundle = intent.getExtras();

070

//反序列化,在本地重建数据

071

Serializable data = bundle.getSerializable("weibodata");

072

073

if (data != null) {

074

weibodatalist = (ArrayList<HashMap<String, String>>)data;

075

076

SimpleAdapter mSchedule = newSimpleAdapter(AndriodFocusMe.this,weibodatalist,

077

R.layout.weibodata_itemview,

078

new String[] {"CreatedAt", "WeiBoText"},

079

new int[] {R.id.title,R.id.weibotext});

080

081

listview.setAdapter(mSchedule);

082

083

} else {

084

return;

085

}

086

} catch (Exception e) {

087

Log.v("test", e.toString());

088

}

089

progressbar.setVisibility(View.GONE);

090

091

}

092

}

093

@Override

094

protected void onStart() {//重写onStart方法

095

//注册用于接收Service传送的广播

096

dataReceiver = new DataReceiver();

097

IntentFilter filter = new IntentFilter();//创建IntentFilter对象

098

filter.addAction("weiboDataChanged");

099

registerReceiver(dataReceiver, filter);//注册Broadcast Receiver

100

NotificationManager m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

101

m_NotificationManager.cancel(R.id.TextView01);

102

super.onStart();

103

104

}

105

@Override

106

protected void onStop() {//重写onStop方法

107

unregisterReceiver(dataReceiver);

108

finish();

109

super.onStop();

110

}

111

112

}

[代码] [Java]代码

001

//继承自Service的子类

002

public class WeiboService extends Service{

003

004

005

//用于判断微博是否有更新标志

006

private boolean newDateFlag = false;

007

008

//微博对象

009

Weibo weibo;

010

011

NotificationManager m_NotificationManager;

012

Notification m_Notification;

013

PendingIntent m_PendingIntent;

014

015

//继承自BroadcastReceiver对象,用于得到Activity发送过来的命令

016

CommandReceiver cmdReceiver;

017

boolean flag;

018

019

//Service命令列表

020

int CMD_STOP_SERVICE = 0;

021

int CMD_RESET_SERVICE = 1;

022

int CMD_GET_WEIBO_DATA = 2;

023

024

@Override

025

public void onCreate() {//重写onCreate方法

026

flag = true;

027

//初始化新浪weibo open api

028

System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);

029

System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);

030

weibo=OAuthConstant.getInstance().getWeibo();

031

//注册时,新浪给你的两个字符串,填写上去

032

weibo.setToken("xxxxxx", "xxxxxxxx");

033

034

m_Notification = new Notification();

035

036

super.onCreate();

037

038

}

039

040

@Override

041

public IBinder onBind(Intent intent) {//重写onBind方法

042

// TODO Auto-generated method stub

043

return null;

044

}

045

046

//前台Activity调用startService时,该方法自动执行

047

@Override

048

public int onStartCommand(Intent intent, int flags, int startId) {//重写onStartCommand方法

049

cmdReceiver = new CommandReceiver();

050

IntentFilter filter = new IntentFilter();//创建IntentFilter对象

051

//注册一个广播,用于接收Activity传送过来的命令,控制Service的行为,如:发送数据,停止服务等

052

//字符串:weibo4andriod.focusme.weiboService为自定义,没有什么要求,一般用包名+文件名,避免重复

053

//如果重复,Android系统在运行期会显示一个接收相同Action的服务程序列表,供用户选择。

054

//注册同一个action的程序,能否同时接收广播,待测试.....

055

filter.addAction("weibo4andriod.focusme.weiboService");

056

//注册Broadcast Receiver

057

registerReceiver(cmdReceiver, filter);

058

doJob();//调用方法启动线程

059

return super.onStartCommand(intent, flags, startId);

060

}

061

//方法:

062

public void doJob(){

063

new Thread(){

064

public void run(){

065

066

ArrayList<HashMap<String,String>> data;

067

while(flag){

068

try{//睡眠一段时间

069

Thread.sleep(5000);

070

}

071

catch(Exception e){

072

e.printStackTrace();

073

}

074

075

data = getWeiboData();

076

077

if(isNewDateFlag()){

078

sendNotification("xxxxxxxxx");

079

080

}

081

setNewDateFlag(false);

082

}

083

}

084

}.start();

085

}

086

//接收Activity传送过来的命令

087

private class CommandReceiver extends BroadcastReceiver{

088

@Override

089

public void onReceive(Context context, Intent intent) {

090

int cmd = intent.getIntExtra("cmd", -1);//获取Extra信息

091

if(cmd == CMD_STOP_SERVICE){//如果发来的消息是停止服务

092

flag = false;//停止线程

093

stopSelf();//停止服务

094

}

095

if(cmd == CMD_RESET_SERVICE){//如果发来的消息是刷新服务

096

097

}

098

if(cmd == CMD_GET_WEIBO_DATA){//如果发来的消息是发送weibo数据

099

sendWeiboData();

100

}

101

}

102

103

104

}

105

@Override

106

public void onDestroy() {//重写onDestroy方法

107

this.unregisterReceiver(cmdReceiver);//取消注册的CommandReceiver

108

super.onDestroy();

109

}

110

111

/**

112

* Get Weibo data

113

*/

114

public ArrayList<HashMap<String,String>> getWeiboData(){

115

116

ArrayList<HashMap<String,String>> weiboDataList

117

= new ArrayList<HashMap<String,String>>();

118

119

HashMap<String, String> map

120

= new HashMap<String, String>();

121

122

List<Status> friendsTimeline;

123

124

try {

125

friendsTimeline = weibo.getUserTimeline();

126

127

for (Status status : friendsTimeline) {

128

129

ofCheckNewWeibo(status.getCreatedAt());

130

131

map = new HashMap<String, String>();

132

map.put("CreatedAt", status.getCreatedAt().toString());

133

map.put("WeiBoText", status.getText());

134

135

weiboDataList.add(map);

136

137

}

138

}

139

catch (WeiboException e) {

140

e.printStackTrace();

141

}

142

return weiboDataList;

143

}

144

145

private void ofCheckNewWeibo(Date createdAt) {

146

// TODO Auto-generated method stub

147

Date weibolastdate;

148

Editor editor;

149

150

//通过SharedPreFerence读取和记录系统配置信息

151

SharedPreferences preferences = getSharedPreferences("weiboDate",Context.MODE_PRIVATE);

152

153

weibolastdate = SParseD(preferences.getString("lastDate","Mon Nov 29 16:08:43 +0800 1900"));

154

155

if(weibolastdate.before(createdAt)){

156

157

editor = preferences.edit();

158

159

editor.putString("lastDate", createdAt.toString());

160

161

editor.commit();

162

setNewDateFlag(true);

163

}

164

}

165

166

/**

167

* 发送有微博更新的通知

168

* @param sendText

169

*/

170

public void sendNotification(String sendText){

171

172

Intent intent = new Intent(WeiboService.this,AndriodFocusMe.class);

173

174

m_Notification.icon=R.drawable.icon;

175

m_Notification.tickerText=sendText;

176

m_Notification.defaults=Notification.DEFAULT_SOUND;

177

178

m_PendingIntent=PendingIntent.getActivity(WeiboService.this, 0,intent, 0);

179

m_Notification.setLatestEventInfo(WeiboService.this, "title","text",m_PendingIntent);

180

m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

181

m_NotificationManager.notify(R.id.TextView01,m_Notification);

182

}

183

184

185

186

187

/**

188

* String to Date

189

* @param date

190

* @return

191

*/

192

//比较数据是否为新的

193

public Date SParseD(String date){

194

String format = "EEE MMM dd HH:mm:ss Z yyyy";

195

SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.US);

196

197

Date parseDate = null;

198

try {

199

parseDate = dateFormat.parse(date);

200

} catch (ParseException e) {

201

// TODO Auto-generated catch block

202

e.printStackTrace();

203

}

204

205

return parseDate;

206

}

207

208

public boolean isNewDateFlag() {

209

return newDateFlag;

210

}

211

212

public void setNewDateFlag(boolean newDateFlag) {

213

this.newDateFlag = newDateFlag;

214

}

215

216

217

//发送微博数据列表

218

public void sendWeiboData() {

219

// TODO Auto-generated method stub

220

ArrayList<HashMap<String,String>> Data;

221

222

Data = getWeiboData();

223

224

Intent intent = new Intent();//创建Intent对象

225

226

Bundle bundle = new Bundle();

227

//序列化列表,发送后在本地重建数据

228

bundle.putSerializable("weibodata",Data);

229

intent.setAction("weiboDataChanged");

230

intent.putExtras(bundle);

231

sendBroadcast(intent);//发送广播

232

}

233

}

赞助本站

人工智能实验室

相关热词: Activity Service

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港