Android studio--from Java thread to Android thread

Source: Internet
Author: User

Write in front:

本文为安卓线程与JAVA线程的异同,请多多指正!

Briefly:

相信很多学安卓的都是从java入门之后开始进行安卓的学习,而当我们面临安卓线程的书写的时候,发现安卓线程并不是我们想象中使用java的线程写法就可以。
    • Wrong syntax porting for Java threads?

Here we simply write a textclock (made up of TextView and calendar), where the button is used to terminate the time. Here we use the Java thread to:

 Public  class mainactivity extends appcompatactivity {    PrivateTextView TextView;Private BooleanFlag =true;//For controlling threads    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);NewThread (NewRunnable () {@Override             Public void Run() { while(flag)                    {Calendar calendar = calendar.getinstance (); Calendar.settimeinmillis (System.currenttimemillis ());inthour = Calendar.get (Calendar.hour_of_day);intminute = Calendar.get (Calendar.minute);intSEC = Calendar.get (Calendar.second); String string =NewString (hour +" : "+ Minute +" : "+ sec);                    TextView = (TextView) Findviewbyid (r.id.test); Textview.settext (Msg.obj.toString ());Try{Thread.CurrentThread (). Sleep ( -); }Catch(Exception e)                    {E.printstacktrace ();        }}}). Start ();        Button button = (button) Findviewbyid (R.ID.BTN); Button.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {flag =false; Toast.maketext (mainactivity. This,"You click here!", Toast.length_short). Show ();    }        }); }}

Now analyze the above case, in the above program there are two threads: a main thread and a sub-thread, their responsibilities.

The processing in the above example uses a child thread to update the UI interface, violating the Android multithreaded programming rules, and the system throws an exception "only the original thread that created a view hierarchy can touch its vie WS ".

To solve this problem, it is necessary to identify the main thread and the responsibilities of the child threads. The main thread's responsibility is to create, display, and update UI controls, handle UI events, start child threads, stop child threads, and the child thread's responsibility is to calculate elapsed time and to issue updated UI messages to the main thread, rather than updating the UI directly.

The responsibility of the main thread is to display UI controls, handle UI events, start child threads, stop child threads, and update the UI, and the child thread's responsibility is to calculate elapsed time and issue updated UI messages to the main thread. But the new problem arises: how do the child threads and the main thread send messages, and how do they communicate?

    • Process child processes with handler and message
      Since the layout is simple, we do not elaborate on the layout code here, the following main activity code:
 Public  class mainactivity extends appcompatactivity {    PrivateTextView TextView;Private BooleanFlag =true;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);/ * Update page with handler * /        FinalAndroid.os.Handler Handler =NewAndroid.os.Handler () {@Override             Public void Handlemessage(Message msg) {Switch(Msg.what) {/ * Receive message*/from sub-threads                     Case 0:{/ * Perform different actions depending on the source * /TextView = (TextView) Findviewbyid (r.id.test); Textview.settext (Msg.obj.toString ());/ * Text update * /}                }Super. Handlemessage (msg);//It's best to throw a message to the parent class that you don't need or care about, to avoid losing the message}        };NewThread (NewRunnable () {//using the Runnable interface to implement Threads            @Override             Public void Run() { while(flag)                    {Calendar calendar = calendar.getinstance (); Calendar.settimeinmillis (System.currenttimemillis ());inthour = Calendar.get (Calendar.hour_of_day);intminute = Calendar.get (Calendar.minute);intSEC = Calendar.get (Calendar.second); String string =NewString (hour +" : "+ Minute +" : "+ sec);//The above is a calculation operationMessage message =NewMessage ();//Initialize Message objectMessage.obj = string;//Add the message you want to send to the messageMessage.what =0;//Set message source to 0Handler.sendmessage (message);//Send a message to handler                    Try{//thread hibernationThread.CurrentThread (). Sleep ( -);//thread represents a thread, CurrentThread () represents getting the current thread, and sleep () represents sleep}Catch(Exception e)                    {E.printstacktrace ();        }}}). Start ();        Button button = (button) Findviewbyid (R.ID.BTN); Button.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {flag =false; Toast.maketext (mainactivity. This,"You click here!", Toast.length_short). Show ();    }        }); }}

For a more specific message mechanism, please visit
The message mechanism of Android (simple summary)-no wind and rain to hide, no bumpy do not have to go · -Blog Channel-csdn.net
http://blog.csdn.net/dadoneo/article/details/7667726

In this way we simply do a timer app that uses threads to successfully implement timings and update data.

    • Using Timetask and handler to achieve
      In the Android platform, you can use the TimerTask class that comes with Java on a recurring basis, and TimerTask is less for resource consumption than for thread, In addition to using the Alarmmanager with Android, using the timer timer is a better solution. We need to introduce import java.util.Timer; and import Java.util.TimerTask;
 Public  class mainactivity extends appcompatactivity {    PrivateTextView TextView;PrivateAndroid.os.Handler Handler;Private BooleanFlag =true; Timer timer =NewTimer ();//Instantiation TimerTimerTask TimerTask =NewTimerTask () {//instantiation of TimerTask        @Override         Public void Run() {Calendar calendar = calendar.getinstance (); Calendar.settimeinmillis (System.currenttimemillis ());inthour = Calendar.get (Calendar.hour_of_day);intminute = Calendar.get (Calendar.minute);intSEC = Calendar.get (Calendar.second); String string =NewString (hour +" : "+ Minute +" : "+ sec); Message message =NewMessage ();//Instance MessagesMessage.obj = string; Message.what =0;        Handler.sendmessage (message); }    };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Handler =NewAndroid.os.Handler () {@Override             Public void Handlemessage(Message msg) {Switch(Msg.what) { Case 0: {TextView = (TextView) Findviewbyid (r.id.test);                    Textview.settext (Msg.obj.toString ()); }                }Super. Handlemessage (msg);        }        }; Timer.schedule (TimerTask, +, -);//Note I.Button button = (button) Findviewbyid (R.ID.BTN); Button.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {flag =false; Toast.maketext (mainactivity. This,"You click here!", Toast.length_short). Show ();    }        }); }}

[Note a]:timer.schedule (new MyTask (), long Time1,long timer2);
The first parameter, which is the TimerTask class, is in the package: import Java.util.TimerTask. The consumer inherits the class and implements the public void run () method, because the TimerTask class implements the Runnable interface.
The second parameter means that when you call the method, the method will inevitably call the run () method in the TimerTask class TimerTask class, which is the difference between the two, which translates into Chinese meaning that, after the user calls the schedule () method, It takes such a long time to execute the run () method for the first time.
The third parameter means that after the first call, the run () method is called once every few hours from the second start.
[Attached:]
The most important step in integrating the internal Office system with the external Web site is to read the data from the OA system and generate the final static page based on the site template. Here you need a timed task, the execution of the loop.
When a technician writes a timed task, it assumes that Timer.schedule (timertask task, long delay) is a repeating task. After running the program found that only run once, always feel that the code in the task is a problem, it took a long time to debug the code has no results.
Read through the Java API and discover:
Note Schedule (timertask task, long delay): Schedules the specified task for execution after the specified delay. The main idea is to execute the task after delaying delay of milliseconds. No mention of repeated executions
Schedule (timertask task, long delay, long period) Comment: schedules the specified task for repeated fixed-delay execution, Begi Nning after the specified delay. The main idea is to repeat the execution of the task after the delay time delay of milliseconds, the period is period milliseconds.
The problem is clear schedule (timertask task, long delay) is executed only once, schedule (timertask task, long delay, long period) is the repeated execution. The key problem is that programmers mistakenly think that schedule is repeated execution, without careful study of the API, on the one hand is not enough English ability, the process of browsing the API can not quickly understand the meaning.

    • Knowledge Point Supplement

Many novice Android or Java developers are still confused with thread, Looper, handler, and message, derived from Handlerthread, Java.util.concurrent, Task, Asynctask as the current literature on the market did not talk about these issues, today on this issue to do a more systematic summary. The service, activity, and broadcast we create are a primary thread processing, which we can understand as a UI thread. However, in the operation of some time-consuming operations, such as I/O read and write large file read and write, database operations and network download takes a long time, in order not to block the user interface, a ANR response prompt window, this time we can consider using thread threads to solve.

For programmers who have engaged in J2ME development, the thread is simpler, directly anonymous create rewrite the Run method, call the Start method execution. or inherited from the Runnable interface, but for the Android platform the UI controls are not designed to be thread-safe, so there is a need to introduce a synchronous mechanism to refresh it, which Google has referred to as the next WIN32 message-handling mechanism when designing Android.

  1. For a thread to refresh a view-based interface, you can use the Postinvalidate () method to process it in the threads, which also provides some overriding methods such as postinvalidate (int
    Left,int top,int Right,int Bottom)
    To refresh a rectangular area, as well as delay execution, such as postinvalidatedelayed (long
    Delaymilliseconds) or postinvalidatedelayed (long delaymilliseconds,int
    Left,int top,int Right,int Bottom) method, where the first parameter is a millisecond

  2. Of course, the recommended method is to handle these through a handler, you can call the handler object's PostMessage or SendMessage method in a thread's Run method, and the Android program maintains a message queue, which rotation handle. If you are a WIN32 programmer can understand these message processing well, but there is no comparison with Android
    PreTranslateMessage these internal methods of interference.

  3. What is Looper again? , in fact, every thread in Android follows a looper,looper to help thread maintain a message queue, but Looper and handler have nothing to do with it. We can see from the open source code that Android also provides a thread inheriting class Handerthread can help us to handle, in the Handlerthread object can get a Looper object control handle through the Getlooper method, We can map this Looper object to a handler to implement a thread synchronization mechanism, The execution of the Looper object requires initialization of the Looper.prepare method, which is the problem we saw yesterday, as well as releasing the resources, using the Looper.release method.

  4. What is Message on Android?
    For Android, Handler can pass some content, and the bundle object can encapsulate string, Integer, and Blob binary objects. We pass a bundle object to the handler processor by using the Sendemptymessage or SendMessage method of the handler object in the thread. The override method is provided for the handler class Handlemessage (Message
    Msg
    To judge by Msg.what to distinguish each piece of information. The bundle is unpacked to implement the handler class to update the contents of the UI thread to implement the refresh operation of the control. Related handler objects related to message sending sendxxxx related methods are as follows, and there are postxxxx related methods, these and Win32 the rationale is basically consistent, one for send after the direct return, one for processing before returning
    .

  5. Java.util.concurrent object analysis, for programmers in the past Java development will not be unfamiliar with concurrent object, he is the JDK 1.5 after the new important features as handheld devices, we do not advocate the use of this class, Considering that Android is a task mechanism that we have designed, there is no too much to repeat here, the related reasons refer to the following description:

  6. There is also an alternative to threading in Android, which is task and asynctask, which can be seen in the open source code for the concurrent package, which developers can easily handle with these asynchronous tasks.

Excerpt from: http://www.cnblogs.com/playing/archive/2011/03/24/1993583.html

Android studio--from Java thread to Android thread

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.