实现过程的主要代码:
-
Click事件中
case
R.id.
add
:
Person person = new Person();person . name = name .getText().toString();person . age =Integer. valueOf ( age .getText().toString());Map param= new HashMap ();param.put( "person" , person ) ;task = new Task(Config. TASK_ADD , param);MainService. addNewTask ( task );break ;case R.id. query :task = new Task(Config. TASK_QUERY , null );MainService. addNewTask ( task );break ;
-
开始执行任务
public
static
void
addNewTask(
final
Task ts) {
new Thread() {public void run() {mainService .doTask(ts);}}.start();}
public void doTask(Task task) {if (task == null )return ;Map param = task.getTaskParam();ArrayList list = new ArrayList<Object>();Message message = handler .obtainMessage();int taskid = task.getTaskID();switch (taskid) {case Config. TASK_ONE :String test = "test" ;message. obj = test;break ;case Config. TASK_ADD :personService .insertPerson((Person)param.get( "person" ));break ;case Config. TASK_QUERY :list= personService .getPersonList();message. obj = list;break ;}message. what = task.getTaskID();handler .sendMessage(message);}
-
PersonService介绍 ,实现增加和查询的功能
public
ArrayList<Person> getPersonList() {
Cursor cursor = dbHelper .query( dbHelper . TB_PERSON , new String[] { "_id" ,"name" , "age" }, null , null , null , null , null , null );ArrayList<Person> list = new ArrayList<Person>();while (cursor.moveToNext()) {Person person = new Person();person. id = cursor.getInt(0);person. name = cursor.getString(cursor.getColumnIndex( "name" ));person. age =cursor.getInt(2);list.add(person);}cursor.close();return list;}public void insertPerson(Person person) {ContentValues cv = new ContentValues();cv.put( "name" , person. name );cv.put( "age" , person. age );dbHelper .insert( dbHelper . TB_PERSON , cv);}
- 返回数据给activity
@Override
public
void
handleMessage(Message msg) {
super
.handleMessage(msg);
IActivity ac =
null
;
String activityName =
""
;
switch
(msg.
what
) {
case
Config.
TASK_ONE
:
activityName =
"AndroidTaskActivity"
;
break
;
case
Config.
TASK_QUERY
:
activityName =
"AndroidTaskActivity"
;
break
;
}
ac = MainService.
getActivityByName
(activityName);
ac.refresh(msg.
what
, msg.
obj
);
}
};
- 显示在当前activity
int
flag = (Integer) param[0];
switch
(flag) {
case
Config.
TASK_ONE
:
String str = (String) param[1];
et
.setText(str);
break
;
case
Config.
TASK_QUERY
:
ArrayList
ls=
new
ArrayList
();
ls=(
ArrayList
) param[1];
Person P=
new
Person();
P=(Person) ls.get(1);
et
.setText(
"name: "
+P.
name
+
" age: "
+P.
age
+
" id: "
+P.
id
);
break
;
}
}