(Android review) basic use of handler

Source: Internet
Author: User

(Android review) basic use of handler


I. Basic knowledge points

1. Intent intent = new Intent (); // open the browser's
Intent. setAction (Intent. ACTION_VIEW );
Intent. setData (Uri. parse ("http://www.baidu.com "));


2. SystemClock. sleep (20000); // sleep for 20 seconds to hide the game


3. Time-consuming operations should be performed in sub-threads
Obtain data online
Copying large files
Must be placed in the sub-thread for operation.


The onCreate () button clicks the callback event and the displayed operations are all run in the main thread. UI thread.


4. handler usage
New Handler ();


Message msg = new Message ();
Msg. what = UPDATE_DISPLAY; // sets unique message recognition.
Msg. obj = I;
MHandler. sendMessage (msg)



Ii. Sample Code

package com.example.handlertest;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.os.SystemClock;import android.app.Activity;import android.view.Menu;import android.view.View;import android.widget.TextView;public class MainActivity extends Activity {public TextView tv_num;public static final int UPDATE_NUMBER = 0;public int i = 0;public Handler handler = new Handler(){public void handleMessage(android.os.Message msg) {if(msg.what == UPDATE_NUMBER){int i = (Integer) msg.obj;tv_num.setText(i + "");}};};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);tv_num = (TextView) findViewById(R.id.tv_number);}public void add(View view){new Thread(){@Overridepublic void run() {super.run();while(i < 100){SystemClock.sleep(1000);i += 1;Message msg = new Message();msg.what = UPDATE_NUMBER;msg.obj = i;handler.sendMessage(msg);}}}.start();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}


3. Download source code

Http://download.csdn.net/detail/caihongshijie6/7798627


IV,




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.