【问题标题】:Unable to access Activity's method from Android AsyncTask无法从 Android AsyncTask 访问 Activity 的方法
【发布时间】:2012-08-08 19:57:20
【问题描述】:

我有一个问题,我需要从 Android AsyncTask 的 onPostExecute() 方法访问我的 Activity 中的方法

我有 2 个活动都包含以下通用方法:

(1) Activity1 --> refreshUI()
(2) Activity2 ----> refreshUI()

我得到了一个AsyncTask 调用GetDataAsyncTask(Activity a ),它将调用活动作为参数

现在从我的活动1中,我将致电新的GetDataAsyncTask(Activity1.this).execute
与我的活动2相同,我将调用新的GetDataAsyncTask(Activity2.this).execute

我的 AsyncTask 如下:

public class GetDataAsyncTask extends AsyncTask<String ,Void , String> {
    public Activity context;

    public PostAsyncTaskHelper(Activity c) { 
        context = c; 
    }

    protected String doInBackground(String... arg0) {
        // Webservice calls 
    }

    protected void onPostExecute(String result) {
        if(result.equals("qq")) {
            //Where I am not able to access refreshUI() 
            //method of any one of my activities
            context.refreshUI()  
        }
    }
}

谁能帮我从AsyncTask获取任何被调用活动的参考?

【问题讨论】:

    标签: android android-layout android-intent android-emulator android-widget


    【解决方案1】:

    创建一个具有refreshUI() 方法的interface,并让Activity1 和Activity2 都实现它。然后,您只需要将context 类型转换为接口的类型。

    此外,您需要小心在 AsyncTask 内部持有对 Activity 的引用,因为在配置更改(如屏幕旋转)的情况下,您将持有已销毁的 Activity实例。 See here 了解详情,example solution 与此对应。

    【讨论】:

      【解决方案2】:

      为您的活动定义接口

      public interface MyActivityRefreshInterface
      {
       public void refreshUI();
      }
      

      您的活动必须定义为implements MyActivityRefreshInterface

      您的 onPostExecute 然后可以将上下文转换为 (MyActivityRefreshInterface)context

      【讨论】:

      • 请务必查看@wsanville cmets re:reference to Activity,我们都以相似的答案同时回答了您的问题,但他的回答更周到
      【解决方案3】:

      因为 refreshUI 不是 Activity 中的方法。它在您特定的 Activity1 和 Activity 2 类中,而不是来自 Android 的 Activity 类。您应该重构 Activity1 和 Activity2 以从具有 refreshUI 方法的 BaseActivity 继承,并将 AsyncTask 中的上下文标记为 BaseActivity

      【讨论】:

        猜你喜欢
        • 2020-05-01
        • 2011-11-27
        • 1970-01-01
        • 1970-01-01
        • 2013-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多