Android服务无法立即启动

时间:2011-04-14 06:17:31

标签: android multithreading service

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");
    }

我希望它会打印出来:

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先生:)

1 个答案:

答案 0 :(得分:2)

那是因为线程在“伪”并行执行,因此在计数器线程获得任何CPU时间之前调用Log.v("Test", "service started?");

“Pseudo” - 并行,因为大多数手机没有超过1个CPU,因此无法并行计算,因此它们只能从一个线程切换到另一个线程。您可以在Wikipedia或您喜欢的任何其他来源上阅读有关线程的更多信息。