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先生:)
不明白你在等什麼,你會得到什麼? – Olegas 2011-04-14 06:28:39
你沒有得到'服務開始'? – Olegas 2011-04-14 06:36:11
是的,我做了,它是在啓動服務後 – 2011-04-14 06:53:01