如何:创建一个在后台运行的服务并调用Handler.sendMessage(.)



我想使用android.app.Service(不是IntentService,不是AsyncTask)来运行我的长时间运行的进程,并在进程中调用Handler.sendMessage(..)。

使用下面的代码是足够的(服务的onCreate方法)?

@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));
    }
}

并且还想问你们,如果所有的回调都将在上面创建的线程上调用?

我如何检查它们是否真的在该线程上运行?有办法检查吗?

您需要实现getter and setter of Handler inside service并从您想要接收其通知的活动设置此处理程序。

最新更新