In-depth questions about Android threads

Source: Internet
Author: User

An application has only one thread.
By default, a process has only one thread, which is consistent with other languages, such as C/C ++ and Java. That is to say, in the Android Application, a process has only one thread, and all components run in one thread!

When an application starts, the system will create a process for it, and a thread name will also be created, including the creation of all its components and the processing of system events, the system callback and other application-related tasks run in the main thread. This thread is commonly known as the main thread ). It is also known as the UI thread, because only the main thread can operate on the UI-related things, so some people call the main thread also called the UI thread, but this is not the correct statement, because the thread to which the Service belongs can also operate Toast, but the Service does not have the UI. Why can't non-main threads operate the UI? Because UI operations often lead to system callbacks, if a third thread is allowed to perform operations, the system callback may be disordered, which in turn will disrupt the time sequence of the entire framework!
All components in the same process run in the same thread. Activiy, Service, BoradcastReceiver, and ContentProvider both run in the main thread.

The most common mistakes are Service. Both documents and common sense think that the Service is used in the background for time-consuming operations, but in fact it is not. If you do time-consuming operations in the Service, it will also lead to the notorious ANR (Application Not Responding ). Therefore, if you want to use the Service as a Server, you must use HandlerThread or Thread in the Service to create a Worker Thread!
The same is true for the Activity. After you start Activity (), you start a new Activity, but they all run in the same thread, so you still cannot perform time-consuming operations in the original Activity! That is, after startActivity () is called to start a new Activity, or time-consuming operations in onPause (), onStop (), onDestroy () will lead to ANR.

The same is true for ContentProvider. If it is in the same process as other components, calling the ContentResolver method is equivalent to directly calling the ContentProvider method. If it is in another process, although it is through IPC, it is also synchronized, because the synchronization of IBinder, that is, when ContentResolver is called, the caller's process will be suspended, wait until the ContentProvider process operation is complete, and then pass the result to the caller process! Therefore, if ContentProvider has time-consuming operations or locks the database synchronously, pay attention to the occurrence of ANR!
So remember: A process has only one thread, and all components are running in the main thread.
Therefore, if there are time-consuming operations, you must create a Worker thread!

Instance
There is a small instance. An application has five components: two activities, one Service, one ContentProvider and one BroadcastReceiver. The thread information of each component is printed in the method. In addition, for Activity, Service, and ContentProvider, if time-consuming operations are performed, ANR is triggered. This is especially true for BroadcastReceiver. Everyone knows this!Copy codeThe Code is as follows: public class ActivityDemo extends Activity {
Private static final String TAG = "ActivityDemo ";
Private Handler mMainHandler = new Handler (new Handler. Callback (){
Public boolean handleMessage (Message msg ){
DumpThreadInfo ();
Return false;
}
});

@ Override
Protected void onCreate (Bundle savedInstanceState ){
DumpThreadInfo ();
Super. onCreate (savedInstanceState );

// Add four buttons
LinearLayout layout = new LinearLayout (getApplication ());
Layout. setOrientation (LinearLayout. VERTICAL );
Button startService = new Button (getApplication ());
StartService. setText ("Start a Service ");
StartService. setOnClickListener (new View. OnClickListener (){
Public void onClick (View v ){
Intent I = new Intent (getApplication (), ServiceDemo. class );
StartService (I );
}
});
Layout. addView (startService );
Button startAnother = new Button (getApplication ());
StartAnother. setText ("Start another Activity ");
StartAnother. setOnClickListener (new View. OnClickListener (){
Public void onClick (View v ){
Intent I = new Intent (getApplication (), AnotherActivity. class );
StartService (I );
}
});
Layout. addView (startAnother );
Button startContentProvider = new Button (getApplication ());
StartContentProvider. setText ("Start a ContentProvider ");
StartContentProvider. setOnClickListener (new View. OnClickListener (){
Public void onClick (View v ){
GetContentResolver (). query (ContentProviderDemo. CONTENT_URI, null );
}
});
Layout. addView (startContentProvider );
Button startReceiver = new Button (getApplication ());
StartReceiver. setText ("Start a BroadcastReceiver ");
StartReceiver. setOnClickListener (new View. OnClickListener (){
Public void onClick (View v ){
Intent I = new Intent ("android. action. start_broadcastreceiver_demo ");
SendBroadcast (I );
}
});
Layout. addView (startReceiver );
SetContentView (layout );

MMainHandler. sendEmptyMessageDelayed (0,500 );
}

Public void dumpThreadInfo (){
Thread. dumpStack ();
Log. e (TAG, Thread. currentThread (). toString ());
Log. e (TAG, "" + getmainlogoff ());
}
}

Copy codeThe Code is as follows: public class AnotherActivity extends Activity {
Private static final String TAG = "AnotherActivity ";
Private Handler mMainHandler = new Handler (getMainLooper (), new Handler. Callback (){
Public boolean handleMessage (Message msg ){
// This will cause ANR
Log. e (TAG, "you know what this is very slow ");
SystemClock. sleep (20*1000 );
DumpThreadInfo ();
Return false;
}
});
@ Override
Protected void onCreate (Bundle savedInstanceState ){
DumpThreadInfo ();
Super. onCreate (savedInstanceState );

SetTitle ("this is another activity ");
MMainHandler. sendEmptyMessageDelayed (0,500 );
}
@ Override
Protected void onDestroy (){
DumpThreadInfo ();
Super. onDestroy ();
}
Public void dumpThreadInfo (){
Thread. dumpStack ();
Log. e (TAG, Thread. currentThread (). toString ());
Log. e (TAG, "" + getmainlogoff ());
}
}

Copy codeThe Code is as follows: public class ServiceDemo extends Service {
Private Handler mMainHandler = new Handler (new Handler. Callback (){
Public boolean handleMessage (Message msg ){
// This will cause ANR, too
Log. e (TAG, "this is very slow you know, slow ");
SystemClock. sleep (20*1000 );
DumpThreadInfo ();
Return false;
}
});
Private static final String TAG = "ServiceDemo ";
@ Override
Public IBinder onBind (Intent arg0 ){
DumpThreadInfo ();
Return null;
}
@ Override
Public void onCreate (){
DumpThreadInfo ();
Super. onCreate ();
MMainHandler. sendEmptyMessageDelayed (0,500 );
}
@ Override
Public int onStartCommand (Intent intent, int flags, int startId ){
DumpThreadInfo ();
Return super. onStartCommand (intent, flags, startId );
}

Public void dumpThreadInfo (){
Thread. dumpStack ();
Log. e (TAG, Thread. currentThread (). toString ());
Log. e (TAG, "" + getmainlogoff ());
}
}

Copy codeThe Code is as follows: public class ContentProviderDemo extends ContentProvider {
Public static final Uri CONTENT_URI = Uri. parse ("content: // com. hilton. inclutiveandroid. app/content ");
Private static final String TAG = "ContentProviderDemo ";
@ Override
Public int delete (Uri arg0, String arg1, String [] arg2 ){
DumpThreadInfo ();
Return 0;
}
@ Override
Public Uri insert (Uri uri, ContentValues values ){
DumpThreadInfo ();
Return null;
}
@ Override
Public boolean onCreate (){
DumpThreadInfo ();
Return false;
}
@ Override
Public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder ){
DumpThreadInfo ();
// It will cause ANR of course
Log. e (TAG, "this is very slow, you know that ");
SystemClock. sleep (20*1000 );
Return null;
}
@ Override
Public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs ){
DumpThreadInfo ();
Return 0;
}

Public void dumpThreadInfo (){
Thread. dumpStack ();
Log. e (TAG, Thread. currentThread (). toString ());
}
@ Override
Public String getType (Uri arg0 ){
Return null;
}
}

Copy codeThe Code is as follows: public class BroadcastReceiverDemo extends BroadcastReceiver {
Private static final String TAG = "BroadcastReceiverDemo ";
@ Override
Public void onReceive (Context context, Intent intent ){
Log. e (TAG, "intent is" + intent );
DumpThreadInfo ();
}

Public void dumpThreadInfo (){
Thread. dumpStack ();
Log. e (TAG, Thread. currentThread (). toString ());
}
}

Related Article

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.