1. First Android activity in a program is a thread, service and activity is also a thread
2. Start a sub-thread in the activity, and the current activity finish destroy off the child line will also run.
3. The thread in the service is similar to the activity service, even if the thread is stopped (to stop the service and then kill the most recently used process), if you kill the process directly, Android will automatically start the service again. At this point, the service thread will continue to run even if it is stopped unless it is shut down)
Start a child thread in activity
public class Secondactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_lout); System.out.println ("The current thread has executed ====secondactivity=====" +thread.currentthread (). GetId ()); New Thread (new Runnable () {@Overridepublic void run () {while (true) { System.out.println ("The current thread executed ==22222==" + Thread.CurrentThread (). GetId ()); try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ()}} }}). Start (); } @Overrideprotected void OnDestroy () {System.out.println ("The current thread has performed a ====== end =====" +thread.currentthread (). getId ()); Super.ondestroy ();} }
The activity finish sub-thread can still run even if the program exits the child thread (unless the most recently used process is killed in Task Manager)
Start a child thread in the service
public class Testservice extends service{@Overridepublic int Onstartcommand (Intent Intent, int flags, int. Startid) {//To Do auto-generated method StubSystem.out.println ("The current thread has performed ====testservice0000=====" +thread.currentthread (). GetId ()) ; New Thread (new Runnable () {@Overridepublic void run () {while (true) { System.out.println ("The current thread executed ==22222==" + Thread.CurrentThread (). GetId ()); try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();}}} ). Start (); return Super.onstartcommand (Intent, flags, Startid); } @Overridepublic void OnDestroy () {System.out.println ("The current thread has performed a =====testservice= end =====" +thread.currentthread (). GetId ()); Super.ondestroy ();} @Overridepublic ibinder onbind (Intent Intent) {//TODO auto-generated method Stubreturn null;}}
The above 3 is in the case of Android 4.4.2 test, other versions have not been tried. If there is a wrong place, please criticize!
Note that the life cycle of the child thread does not end the activity. Friend processing the returned results to the UI would be problematic, and could provide a little thought for time-consuming or long-running situations
Android activity and child threads in service (entry level)