开发者

Running multiple threads in a Service

I'm trying to run threads simultaneously. I followed the services guide on the Android developers site (http://developer.android.com/guide/topics/fundamentals/services.html).

I modified the code slightly so that instead of just waiting 5 seconds, every second a message is logged.

The output is: msg1 msg1 msg1 msg1 msg1

The problem is that I can't figure out how to run two of these threads at the same time, such that the output is: msg1 msg2 msg1 msg2....

I keep getting msg1 msg1 msg1 msg1 msg1 msg2 msg2 msg2...

He开发者_JS百科re is the code from my onStartCommand():

@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
    Log.v("testService","onStartCommand()");

    new Thread() {
        // This method is called when the thread runs
        public void run() {
            Message msg = mHandler.obtainMessage();
            msg.arg1 = startId;
            mHandler.sendMessage(msg);
        }
    }.start();

    return START_STICKY;
}

Shouldn't this create a new thread for each request so that the previous request isn't block?


It will create a new Thread to send each request to the Handler, but the code for the Handler will execute on whatever Thread instantiated the Handler, not the Thread that sends the message. The whole point of Handlers is to provide a simple method for inter-thread communication.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜