AsyncQueryHandler上的异常处理

Bad*_*ion 2 android exception-handling

使用Android的时AsyncQueryHandler,是否有任何简单的方法来处理从异步插入引发的异常,还是我需要编写自己的该类版本?

Bad*_*ion 6

随便看看AsyncQueryHandler源代码,很明显,我可以扩展它来满足我的需求,而不会感到太多痛苦。由于“ AsyncQueryHandler异常处理”在google或SO上没有给您太多帮助,因此我在下面附加了我的源代码,以防其他任何人遇到相同的情况。

基本上,它的作用是扩展它AsyncQueryHandler的内部工作线程,并super.handleMessage在try-catch块中包装对该线程的调用,然后将所有捕获的异常发送回一条消息中的主线程,并在该消息中传递给onError回调。默认值onError只是重新引发异常。

/**
 * Thin wrapper around @link {@link AsyncQueryHandler} that provides a callback to be invoked 
 * if the asynchronous operation caused an exception.
 */
public class SturdyAsyncQueryHandler extends AsyncQueryHandler {
    public SturdyAsyncQueryHandler(ContentResolver cr) {
        super(cr);
    }

    /**
     * Thin wrapper around {@link AsyncQueryHandler.WorkerHandler} that catches any <code>RuntimeException</code>
     * thrown and passes them back in a reply message. The exception that occurred is
     * in the <code>result</code> field.
     */
    protected class SturdyWorkerHandler extends AsyncQueryHandler.WorkerHandler {
        public SturdyWorkerHandler(Looper looper) {
            super(looper);
        }
        @Override
        public void handleMessage(Message msg) {
            try {
                super.handleMessage(msg);
            } catch (RuntimeException x) {
                // Pass the exception back to the calling thread (will be in args.result)
                WorkerArgs args = (WorkerArgs) msg.obj;
                Message reply = args.handler.obtainMessage(msg.what);
                args.result = x;
                reply.obj = args;
                reply.arg1 = msg.arg1;
                reply.sendToTarget();
            }
        }
    }

    @Override
    protected Handler createHandler(Looper looper) {
        return new SturdyWorkerHandler(looper);
    }

    /**
     * Called when a runtime exception occurred during the asynchronous operation. 
     * <p>
     * The default re-throws the exception
     * @param token - The token that was passed into the operation
     * @param cookie - The cookie that was passed into the operation
     * @param error - The <code>RuntimeException</code> that was thrown during 
     * the operation
     */
    public void onError(int token, Object cookie, RuntimeException error) {
        throw error;
    }

    @Override
    public void handleMessage(Message msg) {
        if (msg.obj instanceof WorkerArgs) {
            WorkerArgs args = (WorkerArgs) msg.obj;
            if (args.result instanceof RuntimeException) {
                onError(msg.what, args.cookie, (RuntimeException) args.result);
                return;
            }
        }
        super.handleMessage(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)