问题描述
|
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);
}
}
};
};
}
谢谢大家特别是对平先生:)
解决方法
那是因为线程是在“伪”并行执行的,所以在计数器线程获得任何CPU时间来写入之前调用
Log.v(\"Test\",\"service started?\");
。
\“ Pseudo \”(并行),因为大多数电话没有超过1个CPU,因此它们无法并行计算,因此只能从一个线程切换到另一个线程。您可以在Wikipedia或您喜欢的任何其他来源上阅读有关线程的更多信息。