新浪微博Android开发(三)

MainService类,执行流程:

代码:

package com.shaccp.logic;

import java.util.ArrayList;
import java.util.List;

import com.shaccp.ui.Home;

import weibo4andriod.Status;
import weibo4andriod.User;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

publicclass MainService extends Service implements Runnable {

publicstatic Weibo weibo =new Weibo();
publicstatic List<Activity> allActivity =new ArrayList<Activity>();
publicstatic List<Task> allTask =new ArrayList<Task>();

publicstatic User nowUser;


publicboolean isrun =true;

publicstatic Activity getActivityByName(String name){

for(Activity ac:allActivity){
if(ac.getClass().getName().indexOf(name)>=0){
return ac;
}
}

returnnull;
}

//启动线程
@Override
publicvoid onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Thread t
=new Thread(this);
t.start();
}


@Override
publicvoid onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}

publicstaticvoid newTask(Task task) {
allTask.add(task);
}


//执行任务,业务逻辑调用,执行完后移出任务
publicvoid doTask(Task task) {

Message mess
= handler.obtainMessage();
mess.what
= task.getTaskId();
System.out.println(
"#####----doTask-----");
try {
switch (task.getTaskId()) {

case Task.TASK_LOGIN:

weibo.setUserId((String)task.getParams().get(
"user"));
weibo.setPassword((String)task.getParams().get(
"pass"));
try {
User u
= weibo.verifyCredentials();
nowUser
= u;
mess.obj
= u;

}
catch (WeiboException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mess.obj
=null;
}

break;

case Task.TASK_GET_TIMELINE:

List
<Status> allStatus = weibo.getFriendsTimeline();
System.out.println(allStatus);
mess.obj
=allStatus;

break;

case Task.TASK_NEW_WEIBO:

break;
}
}
catch (WeiboException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

handler.sendMessage(mess);
//发送消息
allTask.remove(task); //执行任务结束,移出任务


}

//侦听任务
@Override
publicvoid run() {
// TODO Auto-generated method stub
while (isrun) {
System.out.println(
"------RUN-----------");
Task lastTask
=null;
if (allTask.size() >0) {
lastTask
= allTask.get(0);
doTask(lastTask);

}

try{Thread.sleep(1000);}catch(Exception e){};
}
}

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
returnnull;
}


//更新UI
private Handler handler =new Handler(){

@Override
publicvoid handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
System.out.println(
"~~~~Handler~~~~~~~~~");
switch (msg.what) {
case Task.TASK_LOGIN:
IWeiboActivity ia
= (IWeiboActivity)getActivityByName("Login");
ia.refresh(msg.what,msg.obj);
break;

case Task.TASK_GET_TIMELINE:
IWeiboActivity ia2
= (IWeiboActivity)getActivityByName("Home");
ia2.refresh(
new Integer(Home.REFRESH_WEIBO),msg.obj);
break;
}
}

};

}
posted @ 2011-06-27 09:54  还是你最好  阅读(1439)  评论(0编辑  收藏  举报