/** handler update data flag */ protected static final int MSG_UPDATE_DATA = 2; protected static final int MSG_INSERT_DB = 0;
public void downloadData() { updateUIThread( MSG_UPDATE_DATA ); mListView.refreshSelf(); }
public void updateUIThread( final int type ) { new Thread( new Runnable() { @Override public void run() { mUIhandler.sendEmptyMessage( type ); } } ).start(); }
/** refresh UI handler */ private Handler mUIhandler = new Handler() { public void handleMessage( android.os.Message msg ) { switch ( msg.what ) { case MSG_UPDATE_DATA: updateListView( ( List<TaskReceiveRspJson> ) TaskDbManager .getData( TaskDbManager.TABLE_TASK_RECEIVE, mQueryByState ) ); break; default: break; } }; };
handler processing method
Message processing code: private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1 : bt.setText("Downloading..."); break; case 2 : Bitmap bm = (Bitmap) msg.obj; iv.setImageBitmap (bm); break; case 3 : Bundle bundle = msg.getData(); String data = bundle.getString("text"); bt.setText(data); break; } } }; Message sending code: method one: Example 1: Message.obtain(handler,1).sendToTarget(); Example 2: Bitmap bm = NetUtil.downloadNewImg(); Message.obtain(handler, 2, bm).sendToTarget(); Example 3: // This message does not carry data, but a piece of code. When the main thread processes this message, it will execute the code it carries without executing other codes. Message.obtain(handler, new Runnable() { public void run() { bt.setText("Download connotation map"); } }).sendToTarget(); Method two: Example 1: handler.obtainMessage(1).sendToTarget(); Example 2: Bitmap bm = NetUtil.downloadNewImg(); handler.obtainMessage(2, bm).sendToTarget(); Method three: Example 1: Message msg = new Message(); msg.what =1; handler.sendMessage(msg); Example 2: Message msg = new Message(); msg.what =2; msg.obj = bm; handler.sendMessage(msg); Example 3: Message msg = new Message(); Bundle data = new Bundle(); data.putString("text", "Downloading..."); msg.what = 3; msg.setData(data); handler.sendMessage(msg); Example 4: // Create a message object with code and send it to the main thread for execution handler.post(new Runnable() { public void run() { // In the main thread, execute when processing messages Toast.makeText( MainActivity.this, "Download finished", Toast.LENGTH_SHORT).show(); } });
Donate to developers
Driven by interest, I write 免费
something with joy and sweat. I hope you like my work and can support it at the same time. Of course, if you have money to support a money field (the love sign in the upper right corner, support Alipay and PayPal donations), if you have no money to support a personal field, thank you.
Thank you for your sponsorship, I will do better!