2011-04-14 105 views
1
public class TestService extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     final Intent service=new Intent(getApplicationContext(),MessageListener.class); 

     Log.v("Test", "Going to start service");  
     startService(service); 
     Log.v("Test", "service started?"); 

    } 
} 

public class MessageListener extends Service { 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.v("Test", "Start Cmd"); 
     intent.setAction("Started"); 
     new Thread(new Runnable() { 

      @Override 
      public void run() { 
       for(int i=100;i<200;i++){ 
        Log.v("Test",i+""); 
       } 

      } 
     }).start(); 
     return START_STICKY; 

    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Log.v("Test", "Create"); 
    } 

我希望它會打印:Android的服務不會立即開始

Start Service 
create 
Start cmd 
print 1->100 
Service Started. 

但是我卻越來越

Start Service 
Service Started. 
create 
Start cmd 
prints 1->100 

爲什麼呢?


我發現問題是由於異步。 startService將在父節點的方法完成後調用。 解決方法是:

public class TestService extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     Intent service=new Intent(getApplicationContext(),MessageListener.class); 

       startService(service); 

       mCheckerHandler.sendEmptyMessageDelayed(MSG_CHECK_SERVICE_RUNNING, 100); 
    } 

    private static final int MSG_CHECK_SERVICE_RUNNING = 0x001122; 

    private Handler mCheckerHandler = new Handler() { 
      public void handleMessage(android.os.Message msg) { 
        if (msg.what == MSG_CHECK_SERVICE_RUNNING) { 
          if (checkServiceRunning()) { 
            //Do something 
          } else { 
            //Send another message to check in the next 100ms 
            sendEmptyMessageDelayed(MSG_CHECK_SERVICE_RUNNING, 100); 
          } 
        } 
      }; 
    }; 
} 

謝謝大家。特別是對Binh先生:)

+0

不明白你在等什麼,你會得到什麼? – Olegas 2011-04-14 06:28:39

+0

你沒有得到'服務開始'? – Olegas 2011-04-14 06:36:11

+0

是的,我做了,它是在啓動服務後 – 2011-04-14 06:53:01

回答

2

這是因爲線程正在執行「pseudo」-parallel,因此Log.v("Test", "service started?");在計數器線程獲得任何CPU時間寫入之前被調用。

「僞」 - 並行,因爲大多數手機沒有超過1個CPU,因此它們不能並行計算,因此它們只能從一個線程切換到另一個線程。你可以閱讀更多關於線程Wikipedia或你喜歡的任何其他來源。

+0

當我不使用線程時,問題仍然存在。 Android文檔表示,該服務將與主要活動在相同的過程中運行。我認爲它會按順序打印? – 2011-04-14 06:30:35

+0

在同一進程中,但不在同一個線程中。 – Olegas 2011-04-14 06:34:48

+0

但文檔還告訴你:「startService()方法立即返回,Android系統調用服務的onStartCommand()方法。」 ;) – alopix 2011-04-14 06:35:48