Multi-thread interaction in android Service
Android services and activities run in the main UI thread. In android threads, only the main thread (UI thread) has its own default message queue. The sub-thread needs to create its own message queue, send the message to the queue, and loop it up and send it to handler for processing.
1. logoff. prepare (); create a message queue for the subthread.
2. logoff. loop (); puts messages into the message queue and loops.
The following is a DEMO that starts the service through the oncreate () method of activity, starts the sub-thread in the service, and sends a message to the main thread for processing.
3. MainActivity. java is as follows:
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
StartService (new Intent (MainActivity. this, ServiceTest. class ));
}
4. ServiceTest. java
Public class ServiceTest extends Service {
Private Handler mHandler = new Handler (){
@ Override
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case 1:
New Thread (){
@ Override
Public void run (){
Log. I ("service", "2nd Threads ");
Logoff. prepare ();
For (int I = 10; I <20; I ++ ){
Toast. makeText (getApplicationContext (), I + "", 0). show ();
Try {
// Thread. sleep (1000 );
} Catch (Exception e ){
// TODO: handle exception
}
}
MHandler. sendEmptyMessage (2 );
Logoff. loop ();
};
}. Start ();
Break;
Case 2:
New Thread (){
@ Override
Public void run (){
Log. I ("service", "3rd Threads ");
Logoff. prepare ();
For (int I = 20; I <30; I ++ ){
Toast. makeText (getApplicationContext (), I + "", 0). show ();
Try {
// Thread. sleep (1000 );
} Catch (Exception e ){
// TODO: handle exception
}
}
MHandler. sendEmptyMessage (3 );
Logoff. loop ();
};
}. Start ();
Break;
Case 3:
OnDestroy ();
Break;
Default:
Break;
}
Super. handleMessage (msg );
}
};
Public ServiceTest (){
// TODO Auto-generated constructor stub
}
@ Override
Public IBinder onBind (Intent intent ){
// TODO Auto-generated method stub
Return null;
}
@ Override
Public void onCreate (){
Log. I ("service", "onCreate ()");
Super. onCreate ();
New Thread (){
@ Override
Public void run (){
Log. I ("service", "first thread ");
Logoff. prepare ();
For (int I = 0; I <10; I ++ ){
Toast. makeText (getApplicationContext (), I + "", 0). show ();
Try {
// Thread. sleep (1000 );
} Catch (Exception e ){
// TODO: handle exception
}
}
MHandler. sendEmptyMessage (1 );
Logoff. loop ();
};
}. Start ();
}
@ Override
Public int onStartCommand (Intent intent, int flags, int startId ){
Log. I ("service", "onStartCommand ");
Return super. onStartCommand (intent, flags, startId );
}
@ Override
Public void onDestroy (){
Log. I ("service", "onDestroy ()");
Super. onDestroy ();
StopSelf ();
}
}
Appendix: demohttp: // download.csdn.net/detail/u014600432/8104521