2015-05-21 80 views
1

我在想我应该在我的Android项目中放置AsyncTask的位置。截至目前,我正在执行一个AsyncTask作为我的活动的一个私人类。我要做的是在每个有网络通话的活动中,我将执行其自己的私人课程AsyncTask。我有几个问题,但Android with ASYNC任务

  1. In The preexecute method it says I can interact with the activity and place a spinner or progress bar. I do this by using My_Activity_Class_Name.this . So my question is does that line of code reference the activity the AsyncTask is called from? If so I believe that will be a static method. How do i actually pass in the instance of the class so I can interact with non static functions?

  2. I want to place all my Async code into one class for its respective needs. My quesiotn though is if i need to return a type back to the class that calls the Async method how can I return a value? Also is this the best practice?

回答

1

你应该让你的内部私人AsyncTask类 - 静态。这是因为否则它会隐含引用您的活动 - 这意味着如果您的活动将被重新创建 - 即。由于配置更改 - 那么您的AsyncTask仍然会保留您的活动引用,导致引用泄漏。这意味着你应该把你的活动的引用传递给ie中的AsyncTask。 AsyncTask的构造函数,并将其保存在WeakReference中(WeakReference/AsyncTask pattern in android)。

So my question is does that line of code reference the activity the ASYNC Task is called from?

是的,但前提是你的AsyncTask类是非静态

If so I beleve that will be a static method. How do i actually pass in the instance of the class so i can interact with non static functions?

它不是一个静态方法,与My_Activity_Class_Name.this您可以访问你的Activity类的非静态方法。

My quesiotn though is if i need to return a type back to the class that calls the Async method how can I return a value? Also is this the best practice?

你可以在你的Activity类上调用一个方法,没有什么问题。请记住,您无法从非UI线程访问UI小部件。因此,从UI线程上调用的onPostExecute更新您的Activity小部件。

+0

当我使类静态时,我得到错误错误:(104,34)错误:非静态变量,这不能从静态上下文中引用。创建一个弱引用将解决这个问题吗? – Esko918

+0

<! - language:lang-js - > – Esko918

+0

@ Esko918是的,而不是在你的Activity中使你的AsyncTask静态,让它成为一个外部类 - 这里是一个例子:https://gist.github.com/rorist/459787 – marcinj