相当于AsyncTask的黑莓类的? [英] BlackBerry class equivalent to AsyncTask?

查看:103
本文介绍了相当于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。所以,当有一个命令从所述服务器,该线程解析它和更新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 ,它的运作良好。但在黑莓手机,因为没有这样的课,我用了<一href="http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/system/Application.html#invokeLater%28java.lang.Runnable%29"相对=nofollow>的invokeLater()选项。通信工作正常,服务器和BB设备之间,但用户界面被冻结在黑莓手机上。

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?

推荐答案

维沙尔是在正确的轨道,却多了几分是需要配合Android的的AsyncTask 。由于枚举和仿制药所不具备的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:

      
  • 在AsyncTask的类必须在UI线程加载。这样做是   自动为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.

执行(参数...)必须在UI线程中调用。

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

不要在preExecute()调用,onPostExecute(结果),   doInBackground(参数...),onProgressUpdate(进步...)手动。

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.)

这篇关于相当于AsyncTask的黑莓类的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆