简体   繁体   English

从Android中的非活动类调用活动的方法

[英]Calling method of activitiy from a non-activity class in android

I'm implementing a class which extends AsyncTask and I perform an http request within this class. 我正在实现一个extends AsyncTask的类,并且在该类中执行一个http请求。 The class is not an Activity and is located in a seperate java file because I want to use this class several times. 该类不是Activity ,并且位于单独的Java文件中,因为我想多次使用该类。

I instantiate an object of this class in my Activity , to execute the http request in a separate thread. 我在Activity实例化了此类的对象,以在单独的线程中执行http请求。 When the thread executes, I want to call a method of my Activity . 当线程执行时,我想调用Activity的方法。

How do I implement this? 我该如何实施? I need the result of the http request in my Activity but I can't handle this so far. 我在Activity需要http请求的结果,但到目前为止我还无法处理。

This is the code for the thread task... 这是线程任务的代码...

public class PostRequest extends AsyncTask<String, Void, String> {
public String result = "";

@Override
protected String doInBackground(String... urls) {
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://bla/index.php?" + urls[0]);
        // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();

        // convert response to string
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

@Override
protected void onPostExecute(String result) {

}
}

And this is part of my Activity code that creates the thread class... 这是我创建线程类的Activity代码的一部分...

public class ListActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);


    PostRequest task = new PostRequest();
    task.execute(new String[] { "action=getUsers" });
    task.onPostExecute(task.result) {

    }
}

public void Display(String result) {
    try {
        JSONArray jArray = new JSONArray(result);
        JSONObject json_data = jArray.getJSONObject(0);
        String value = json_data.getString("name");
        TextView text = (TextView) findViewById(R.id.value);
        text.setText(value);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
}

pass the activity reference in constructor...... 通过构造函数中的活动引用...

as

public class PostRequest extends AsyncTask<String, Void, String> {
public String result = "";
private Activity mActivity;

 public PostRequest(Activity activity){
          super();
         mActivity = activity;
}

......

You don't have to do a onPostExecute() as this is called after the process doInBackground has completed and then you can use the reference of the activity passed into the constructor of the AsyncTask to run any time of method on your UI. 您不必执行onPostExecute()因为在流程doInBackground完成后会调用此方法,然后您可以使用传递给AsyncTask的构造函数的活动的引用在UI上随时运行方法。

Just remember that onPostExecute() method runs on a UI thread so here from this method you can try to modify your view if needed. 只要记住onPostExecute()方法是在UI线程上运行的,因此在此方法中,您可以根据需要尝试修改视图。

See this question... can-i-put-asynctask-in-a-separate-class-and-have-a-callback and the accepted answer. 看到这个问题。。。 我可以在一个单独的类中放置asynctask并进行回调和接受的答案。 If you want a re-usable AysncTask as a stand-alone class then using a listener as a callback for all of your activities is the best way to do it. 如果希望将可重用的AysncTask作为独立类使用,则将侦听器用作所有活动的回调是最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM