在AsyncTask的类getApplicationContext? [英] getApplicationContext in AsyncTask class?
问题描述
我有一对夫妇的私人AsyncTask的方法,我想闯入了公众的外部类。在我的应用程序,我有一个公共类扩展应用程序,它拥有一些共同套路我想从我的应用程序的不同部分来访问。当我不过打出来的AsyncTask的课,我不再能够调用getApplicationContext()来获取一个引用我的应用程序库(类没有现在继承自Activity东西)。 getBaseContext()会出现问题也是如此。我应该通过上下文到AsyncTask的,当它被实例化,并建立从那里?不知道这是否是安全与否。
进口的java.util.ArrayList;
进口android.os.AsyncTask;
公共类dlTask扩展的AsyncTask
{
长totalbytes = 0;
长totalread = 0;
ArrayList的<字符串>数据;
@覆盖
在preExecute保护无效()
{
AppLib LIB =(AppLib)getApplicationContext();
lib.saveStatusText(联系+ lib.getServerAddress()+:+ lib.getServerPort()+...);
super.on preExecute();
}
@覆盖
保护对象doInBackground(对象... PARAMS)
{
数据= lib.sendCommand(CMD_LIST);
返回true;
}
@覆盖
保护无效onPostExecute(对象结果)
{
如果(数据!= NULL)
{
lib.saveStatusText(data.size()+文件中找到);
}
其他
{
Log.d(TAG,数据为空);
Toast.makeText(getBaseContext(),味精,Toast.LENGTH_SHORT).show();
}
super.onPostExecute(结果);
}
}
我应该通过上下文到AsyncTask的,当它被实例化,并建立从那里?
您没有选择,因为你将无法获得上下文
通过任何其他方式。
I have a couple private AsyncTask methods that I'd like to break out into public external classes. In my application, I have a public class extending Application which holds some shared routines I want to access from different parts of my application. When I break out the AsyncTask class however, I'm no longer able to call getApplicationContext() to get a reference to my application library (the class does not inherit anything from Activity now). getBaseContext() will have problems as well. Should I be passing a context into the AsyncTask when it gets instantiated and build from there? Not sure if that was safe or not.
import java.util.ArrayList;
import android.os.AsyncTask;
public class dlTask extends AsyncTask
{
long totalbytes = 0;
long totalread = 0;
ArrayList <String> data;
@Override
protected void onPreExecute ()
{
AppLib lib = (AppLib) getApplicationContext();
lib.saveStatusText ("Contacting " + lib.getServerAddress () + ":" + lib.getServerPort () + "...");
super.onPreExecute ();
}
@Override
protected Object doInBackground (Object... params)
{
data = lib.sendCommand (CMD_LIST);
return true;
}
@Override
protected void onPostExecute (Object result)
{
if (data != null)
{
lib.saveStatusText (data.size () + " files found");
}
else
{
Log.d (TAG, "data is null");
Toast.makeText (getBaseContext(), msg, Toast.LENGTH_SHORT).show ();
}
super.onPostExecute(result);
}
}
Should I be passing a context into the AsyncTask when it gets instantiated and build from there?
You do not have a choice, as you will be unable to get a Context
by any other means.
这篇关于在AsyncTask的类getApplicationContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!