为UI和后台任务编写代码的正确方式


  1. 如何正确管理android应用程序的代码?(用于任务/UI(
  2. 如何将用户界面与代码分离?(使用类或打包(
  3. 如何从后台线程/操作(correct way(向用户界面添加项目例如,i具有TableLayout。如何正确地将行添加到该TableLayout?根据我的需要创建自定义对象(类(,然后将项目添加到对象中然后在整个对象中循环并将项目添加到TableLayout?是否将TableLayout作为参考
  4. 最好创建单独的class还是package用于数据收集?(连接到数据提供商,获取数据,向用户显示(

我四处寻找,找到了一些做后台任务的方法
-首先是AsyncTask。这里写着,AsyncTasks should ideally be used for short operations (a few seconds at the most.)
-我找到的第二个是汉德勒
-有没有其他正确的方法来完成后台任务?

Witch方式对从WEB服务收集数据是正确的(可能会有一些延迟和滞后(?如果使用Handler,那么如何将数据传递到UI线程?。在大多数情况下,我对第三个问题感兴趣。

谢谢。

设计Android应用程序的结构有很多方法。你的问题很笼统,所以我的回答也是。

为了构建您的项目,您可以使用MVC模式,它可以很容易地与Android:一起使用

  • 模型:主要保存数据,如列表、数组、字符串等
  • 控制器:处理模型的数据,运行逻辑
  • 视图:用户界面,可以显示模型中的数据和/或运行控制器中的逻辑

这个问题,是用包还是类分开,一般都无法回答。两者在许多情况下都很有用。在我看来,以下结构作为一个简单的例子是有用的:

  • [Package]视图:
    • Activty1.java
    • Activty2.java
  • 【包装】型号:
    • Activty1DataModel.java
    • Activty2DataModel.java
  • [包装]控制器:
    • Activty1Logic.java
    • Activty2Logic.java

较重的任务应该在Android上的AsyncTaks上运行,而不是在UIThread上运行(例如,因为GUI冻结(。AsyncTask在一个新的独立线程中运行操作。onPostExecute方法在完成任务后执行,并在UI线程上运行,因此您可以直接从这里与视图交互。

对于真正长时间运行的任务,应该使用后台服务。

当你想从另一个线程与UI交互时,你必须在UI线程上运行显式的操作,例如:

MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
       Log.d("UI thread", "I am the UI thread");
   }
});

与UI交互的另一种方式是使用Interfaces/Listeners

要从web服务收集数据,可以使用带有AsyncTask的http客户端,但不能从UI线程运行网络操作(这会导致异常(。下面是一个例子。

下次请在不同的帖子中提出几个问题,而不是一个问题。

1(。问题不清楚。如果你是认真的话,你会为每个类使用自己的.java文件。

2( 。使用多个程序包。

3( 。我认为从后台更新UI的最佳方式是使用界面。下载图像的示例(使用HttpClient(:

  public class AsyncImageSetter extends AsyncTask<String, Void, Bitmap> {
private onImageLoaderListener listener;
private String msg, server;
public AsyncImageSetter(onImageLoaderListener listener) {
    this.listener = listener;
}
/* the onImageLoaded callback will be invoked on UI thread */
public interface onImageLoaderListener {
    void onImageLoaded(Bitmap bmp, String response);
}
@Override
protected Bitmap doInBackground(String... params) {
    HttpParams hparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(10000);
    HttpConnectionParams.setSoTimeout(10000);
    server = params[0];
    HttpGet get = new HttpGet(server);
    try {
        DefaultHttpClient client = new DefaultHttpClient(hparams));
        HttpResponse response = null;
        /** set cookies if you need it */
        CookieStore store = client.getCookieStore();
        HttpContext ctx = new BasicHttpContext();
        store.addCookie(yourSavedCookieObject);
        ctx.setAttribute(ClientContext.COOKIE_STORE, store);
        response = client.execute(get);
        msg = response.getStatusLine().toString();
        HttpEntity responseEntity = response.getEntity();
        BufferedHttpEntity httpEntity = null;
        try {
            httpEntity = new BufferedHttpEntity(responseEntity);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        InputStream imageStream = null;
        try {
            imageStream = httpEntity.getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return BitmapFactory.decodeStream(imageStream);
    } catch (Exception ex) {
        ex.printStackTrace();
        //error handling
        return null;
    }
}
 /* use this method if your backend sets some pre-defined messages. /*
 /* In my case that would be "Warning */
private void checkResponse(HttpResponse response) {
    Header[] headers = response.getAllHeaders();
    final String target = "Warning";
    for (Header h : headers) {
        if (h.getName().equalsIgnoreCase(target)) {
            msg = h.getValue();
        } else {
            continue;
        }
    }
}
@Override
protected void onPostExecute(Bitmap result) {
    super.onPostExecute(result);
    /* now this callback is invoked on UI thread */
    /* if everything went without errors, you'll get an image and "HTTP 200 OK" in msg */
    if (listener != null) {
        listener.onImageLoaded(result, msg);
    }
 }
}

您需要传递一个new onImageLoaderListener并覆盖onImageLoaded回调,在那里您将获得图像和服务器消息。

4( 。您基本上会使用自己的包,其中包含在后台中执行一些工作的类

最新更新