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);
}
}
};
};
}
Спасибо всем вам. Особенно мистеру Бинху:)