Android service and multithreading, and android service Multithreading
The android service runs in the main UI thread. Here is the code demo:
package com.example.testservice;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService(new Intent(MainActivity.this,ServiceTest.class)); } @Override public 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; } }
Package com. example. testservice; import android. app. service; import android. content. intent; import android. OS. handler; import android. OS. IBinder; import android. OS. logoff; import android. OS. message; import android. util. log; import android. widget. toast; public class ServiceTest extends Service {private Handler mHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {switch (msg. what) {case 1: new Thread () {@ Overridepublic 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 () {@ Overridepublic 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 }@ Overridepublic IBinder onBind (Intent intent) {// TODO Auto-generated method stubreturn null;} @ Overridepublic void onCreate () {Log. I ("service", "onCreate ()"); super. onCreate (); new Thread () {@ Overridepublic 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 () ;}@ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {Log. I ("service", "onStartCommand"); return super. onStartCommand (intent, flags, startId) ;}@ Overridepublic void onDestroy () {Log. I ("service", "onDestroy ()"); super. onDestroy (); stopSelf ();}}
Demo: http://download.csdn.net/detail/u014600432/8104521