Android: How to: create a service running in the background and call Handler.sendMessage(..)
I want to use the android.app.Service (not IntentService, not AsyncTask) to run my long running process and calling Handler.sendMessage(..) during the process.
using the below code is enough (Service's onCreate method)?
@Override
public void onCreate() {
new Thread(new Runnable() {
@Override
public void run() {
Log.w(LOG_LOGCAT_TAG, "DEBUG MODE - CallbackImpl handleError() called");
// get the location information (lat,lon,altitude etc..)
// then, call callback methods.
_locationProvider.getLocation(_locationCallbackImpl);
}
}).start();
}
private final LocationCallbackImpl _locationCallbackImpl = new LocationCallbackImpl();
private class LocationCallbackImpl
implements
LocationCallback
{
@Override
public void done() {
Log.i(LOG_LOGCAT_TAG, "LocationCallbackImpl done() called");
// switch to UI thread
_handler.sendMessage(_handler.obtainMessage(DONE_MESSAGE));
}
@Override
public void handleError(ReturnCode returnCode) {
Log.e(LOG_LOGCAT_TAG, "LocationCallbackImpl handleError() called:" + returnCode.name());
// send a message to display the error
_handler.sendMessage(_handler.obtainMessage(ERROR_MESSAGE, returnCode));
}
@Override
public void handleSuccess(Location location) {
Log.i(LOG_LOGCAT_TAG, "LocationCallbackImpl handleSuccess() called");
_handler.sendMessage(_handler.obtainMessage(LOCATION_MESSAGE, location));
}
}
And 开发者_如何学JAVAwould like also to ask you guys, if all the callbacks will be called on the above created thread?
How can I check if they are really running on that thread? is there a way to check it?
You need to implement getter and setter of Handler inside service
and set this handler from the activity where you want to receive it's notification.
精彩评论