Android ListView刷新 (Handler/Service)

本文转自http://blog.sina.com.cn/s/blog_493c76100100t6f2.html

近期在网上看了下Android的刷新问题,大家都在讨论 invalidate 和 postInvalidate 。想必大家都试用过了,  invalidate是针对UI线程,postInvalidate是针对非UI线程。 
不知同行们有没有过这种想法,用后台的Service调取Activity的Handler进行局部view的刷新?新手们可能会想到在Service里直接调取当前活动的Activity的静态方法不就行了,可是这样会违反了单线程的不安全问题,导致应用直接关闭。而Handler是运行在Activity UI主线程中,如同一个线程。它可以与子线程互相通信,对主线程的UI进行数据的操作。
Handler可以对 Message对象和Runnable对象 进行操作。您可以灵活使用Handler中的一些方法,如:post(Runnable) 和sendMessage(Message)等。
这里给大家一个些代码,请参考。代码很菜,请指教谢谢。

public class RefreshMain extends Activity {

private ListView changeList = null;
private ListAdapter adapter = null;
private RefreshService refreshService = null;

public Handler messageHandler;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

changeList = (ListView) findViewById(R.id.refresh_list);
adapter = new ListAdapter(this);
changeList.setAdapter(adapter);

}

@Override
public void onStart() {
super.onStart();
Looper looper = Looper.myLooper();
messageHandler = new MessageHandler(looper, changeList, this);
}

@Override
public void onResume() {
super.onResume();
bindService();
}

@Override
public void onDestroy() {
unBindService();
super.onDestroy();
}

private boolean _service_bind = false;
private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("refreshService", "_service is Bind.");
refreshService = ((RefreshService.ServiceBinder) service)
.getService();
refreshService.setActivity(RefreshMain.this);
}

public void onServiceDisconnected(ComponentName name) {
refreshService = null;
}
};

private void bindService() {
Intent intentService = new Intent(RefreshMain.this,
RefreshService.class);
RefreshMain.this.startService(intentService);
RefreshMain.this.bindService(intentService, serviceConnection,
Context.BIND_AUTO_CREATE);
_service_bind = true;
}

private void unBindService() {
if (refreshService != null) {
refreshService.stopService();
}
if (_service_bind) {
RefreshMain.this.unbindService(serviceConnection);
_service_bind = false;
}
Intent intentService = new Intent(RefreshMain.this,
RefreshService.class);
this.stopService(intentService);
}
}

public class ListAdapter extends BaseAdapter {

private LayoutInflater listInflater;

List<Map<String, Object>> listData = null;

public final class DataView {

public TextView viewTitle;
public TextView viewTime;
public TextView viewContent;
}

public ListAdapter(Context context) {

this.listInflater = LayoutInflater.from(context);
listData = getData();
}

public int getCount() {
return listData.size();
}

public Object getItem(int position) {
return listData.get(position);
}

public long getItemId(int position) {
return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
DataView item = null;
if (convertView == null) {
item = new DataView();
convertView = listInflater.inflate(R.layout.refresh_list, null);
item.viewTitle = (TextView) convertView.findViewById(R.id.refresh_title);
item.viewTime = (TextView) convertView.findViewById(R.id.refresh_time);
item.viewContent = (TextView) convertView.findViewById(R.id.refresh_content);
convertView.setTag(item);
} else {
item = (DataView) convertView.getTag();
}

item.viewTitle.setText((String) listData.get(position).get("title"));
item.viewTime.setText((String) listData.get(position).get("time"));
item.viewContent.setText((String) listData.get(position).get("content"));

return convertView;
}

private List<Map<String, Object>> getData() {

List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
Map<String, Object> map = null;
for (int i = 1; i <= 5; i++) {
map = new HashMap<String, Object>();
map.put("title", "title " + i);
map.put("time", String.valueOf(System.currentTimeMillis()));
map.put("content", "content " + i + " / " + String.valueOf(System.currentTimeMillis()));
data.add(map);
}
return data;
}

}

public class MessageHandler extends Handler {

private ListView listView;
private RefreshMain activity;

public MessageHandler(Looper looper, ListView _listView,
RefreshMain _activity) {
super(looper);
listView = _listView;
activity = _activity;
}

@Override
public void handleMessage(Message msg) {
//这里大家集思广益,我在这儿偷懒了,嘿嘿
ListAdapter adapter = new ListAdapter(activity);
listView.setAdapter(adapter);

}
}

public class RefreshService extends Service {
private boolean started;

private boolean threadDisable = false;

private Activity _activity = null;

private ServiceBinder serviceBinder = new ServiceBinder();

public class ServiceBinder extends Binder {

RefreshService getService() {
return RefreshService.this;
}
}

public boolean isStarted() {
return started;
}

public void stopService() {
started = false;
}

public void setActivity(Activity activity) {
_activity = activity;
}

@Override
public void onStart(Intent intent, int startId) {
started = true;
Log.i("RefreshService", "service started.");
}

@Override
public IBinder onBind(Intent intent) {
Log.i("RefreshService", "service onBind.");
return serviceBinder;
}

@Override
public boolean onUnbind(Intent i) {
started = false;
return started;
}

@Override
public void onCreate() {
super.onCreate();

Thread thread = new Thread() {
@Override
public void run() {
while (!threadDisable) {
try {
Thread.sleep(10000);
if (started) {
//这里不用我说吧。取前当前活动Activity哈。
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;

if("com.sh.RefreshMain".equals(cn.getClassName())){
((RefreshMain)_activity).messageHandler.sendMessage(Message.obtain());;
}
}
} catch (InterruptedException e) {
}
}
}
};

thread.start();

Log.i("RefreshService", "service created.");
}

@Override
public void onDestroy() {
super.onDestroy();
threadDisable = true;
Log.i("RefreshService", "service shutdown.");
}

}
xml 就不用发了吧,大家可以配一下喽。

你可能感兴趣的:(Android ListView刷新 (Handler/Service))