English 中文(简体)
Android:从特定深层中执行的方法
原标题:Android: Executing method from specific thread
  • 时间:2012-05-19 16:18:58
  •  标签:
  • java
  • android

I m developing an application in Android. The application can post a HTTP request to specific web server. That post request must run asyncronously, so I create a thread to do the job. But I need a callback that will be called at thread end and it must be called from thread that call the `post` method.

缩略语 方法如下:

interface EndCallback
{
    public void Success(String response);
    public void Fail(Exception e);
}

public void post(final String url, final List<NameValuePair> data, EndCallback callback)
{
    Thread t = Thread.currentThread();
    (new Thread()
    {
        public void run()
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            try
            {
                httppost.setEntity(new UrlEncodedFormEntity(data));
                HttpResponse r = httpclient.execute(httppost);

                HttpEntity en = r.getEntity();
                String response = EntityUtils.toString(en);

                //I want to call callback.Success(response)
                //here from thread t
            } 
            catch (Exception ex)
            {
                //And I want to call callback.Fail(ex)
                //here from thread t
            }
        }
    }).start();
}
最佳回答

大部分应用都受到劝阻,因此,创建新型的安乐器。 这似乎与“AsyncTask 。 它有内在的方法,在校对之间转换,无需人工管理翻新。

One approach I ve used in a similar situation is to combine the task with an enum of possible success states:

class HttpPostTask extends AsyncTask<Void, Void, ResponseStatus> {

    @Override
    protected ResponseStatus doInBackground( Void... params ){

        try {
            // do your HTTP stuff
            return ResponseStatus.SUCCESS;
        } catch( Exception e ){
            return ResponseStatus.FAILURE;
        }

    }

    @Override
    protected void onPostExecute( ResponseStatus status ){
        switch( status ){
        case SUCCESS:
            // run your success callback
            break;
        case FAILURE:
            // run the failure callback
            break;
        }
    }

}

enum ResponseStatus {
    SUCCESS,
    FAILURE
}

The doInBackground method will be run in a separate thread, managed by the OS. When that thread finishes, onPostExecute will be run on the thread that started the task, which is typically the UI thread.

如果你需要设置备用物体,就只增加HttpPostTask的建筑商,并做你们所需要的任何初步工作。 那么,你的客户法典就迫切需要制定和实施任务:

new HttpPostTask().execute();

You can also pass parameters into execute() as well, which accepts a variable number of arguments of the first generic type in the class signature. The params variable in the doInBackground is an array of things that were passed into execute, all of the same type.

如果你想把灯带上多个URLs,那么通过密码<>execute是有用的。 对大多数受扶养人而言,将其安置在建筑商是最简单的做法。

问题回答

You may want to use a Handler. Handler is used to post requests to GUI thread.

为了成功处理,使用以下代码:

final Handler successHandler = new Handler()
{
    @Override
    public void handleMessage(Message message)
    {
        callback.Success(response);
    }
};

successHandler.sendEmptyMessage(0);




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签