BlackBerry 类相当于 AsyncTask?

BlackBerry class equivalent to AsyncTask?(BlackBerry 类相当于 AsyncTask?)

本文介绍了BlackBerry 类相当于 AsyncTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是有一个线程来维护 BlackBerry 设备和服务器之间的套接字连接并交换命令,类似于请求和响应.

My requirement is to have a thread that maintains a socket connection between a BlackBerry device and a server and exchanges commands, similar to request and response.

我的问题是我需要让这个线程一直在后台运行并保持用户界面可用.因此,当有来自服务器的命令时,该线程会对其进行解析并更新 UI,如果有来自 BlackBerry 用户的操作,它会将其发送到服务器,然后服务器会依次处理它.

My problem is that I need to have this thread running in the background all the time and keep the UI available to the user. So, when there is a command from the server, this thread parses it and updates the UI and also if there's an action from the BlackBerry user, it sends it to the server and the server in turn handles it.

我使用 AsyncTask 在 Android 中开发了相同的应用程序,并且运行良好.但是在黑莓中,由于没有这样的类,我使用了 invokeLater() 选项.服务器和 BB 设备之间的通信工作正常,但用户界面在 BlackBerry 上被冻结.

I developed the same application in Android using AsyncTask and it's working well. But in BlackBerry, as there's no such class, I used the invokeLater() option. The communication works fine between the server and the BB device, but the UI is frozen on the BlackBerry.

有人知道如何正确处理吗?

Anyone have any idea how to get this right?

推荐答案

Vishal 走在正确的轨道上,但还需要更多一点来匹配 Android 的 AsyncTask.由于 BlackBerry 上的 Java 1.3 不提供枚举和泛型,因此您无法完美匹配 Android API.

Vishal is on the right track, but a little more is needed to match Android's AsyncTask. Since enums and generics aren't available with Java 1.3 on BlackBerry, you can't match the Android API perfectly.

但是,您可以执行以下操作(未测试...这只是您的起点):

But, you could do something like this (not tested ... this is just a starting point for you):

import net.rim.device.api.ui.UiApplication;

public abstract class AsyncTask {

    public static final int FINISHED = 0;
    public static final int PENDING = 1;
    public static final int RUNNING = 2;

    private int _status = PENDING;
    private boolean _cancelled = false;
    private Thread _worker;

    /** subclasses MUST implement this method */
    public abstract Object doInBackground(Object[] params);

    protected void onPreExecute() {
        // default implementation does nothing
    }
    protected void onPostExecute(Object result) {
        // default implementation does nothing
    }
    protected void onProgressUpdate(Object[] values) {
        // default implementation does nothing
    }
    protected void onCancelled() {
        // default implementation does nothing
    }
    protected void onCancelled(Object result) {
        onCancelled();
    }

    public final int getStatus() {
        return _status;
    }

    public final boolean isCancelled() {
        return _cancelled;
    }

    public final boolean cancel(boolean mayInterruptIfRunning) {
        if (_status == FINISHED || _cancelled) {
            return false;
        } else {
            _cancelled = true;
            if (mayInterruptIfRunning && _status == RUNNING) {
                // NOTE: calling Thread.interrupt() usually doesn't work
                //   well, unless you don't care what state the background
                //   processing is left in.  I'm not 100% sure that this is how
                //   Android's AsyncTask implements cancel(true), but I 
                //   normally just cancel background tasks by letting the
                //   doInBackground() method check isCancelled() at multiple
                //   points in its processing.
                _worker.interrupt();
            }
            return true;
        }
    }

    protected final void publishProgress(final Object[] values) {
        // call back onProgressUpdate on the UI thread
        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run() {
                onProgressUpdate(values);
            }
        });
    }

    private void completeTask(final Object result) {
        // transmit the result back to the UI thread
        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run() {
                if (isCancelled()) {
                    onCancelled(result);
                } else {
                    onPostExecute(result);
                }
                // TODO: not sure if status should be FINISHED before or after onPostExecute()
                _status = FINISHED;
            }
        }); 
    }

    public AsyncTask execute(final Object[] params) throws IllegalStateException {
        if (getStatus() != PENDING) {
            throw new IllegalStateException("An AsyncTask can only be executed once!");
        } else {
            try {
                onPreExecute();

                _worker = new Thread(new Runnable() {
                    public void run() {
                        try {
                            // run background work on this worker thread
                            final Object result = doInBackground(params);
                            completeTask(result);
                        } catch (Exception e) {
                            // I believe if Thread.interrupt() is called, we'll arrive here
                            completeTask(null);
                        }
                    }
                });
                _status = RUNNING;
                _worker.start();
            } catch (Exception e) {
                // TODO: handle this exception
            }
        }

        return this;
    }

}

此外,记住 Android 的 AsyncTask 的线程规则也很重要,这些规则也适用于上述实现:

Also, it's important to keep in mind the Threading Rules for Android's AsyncTask, which apply to the above implementation, too:

线程规则有一些线程规则必须遵守为了让这个类正常工作:

Threading rules There are a few threading rules that must be followed for this class to work properly:

  • 必须在 UI 线程上加载 AsyncTask 类.这个完成了自动从 JELLY_BEAN 开始.

  • The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.

任务实例必须在UI 线程.

The task instance must be created on the UI thread.

execute(Params...) 必须在 UI 线程上调用.

execute(Params...) must be invoked on the UI thread.

不要调用 onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...) 手动.

Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.

任务只能执行一次(如果尝试第二次执行.)

The task can be executed only once (an exception will be thrown if a second execution is attempted.)

这篇关于BlackBerry 类相当于 AsyncTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:BlackBerry 类相当于 AsyncTask?

基础教程推荐