Android 将参数传递给 TimerTask 扩展类
Posted
技术标签:
【中文标题】Android 将参数传递给 TimerTask 扩展类【英文标题】:Android pass parameters to TimerTask extends class 【发布时间】:2014-11-14 18:34:54 【问题描述】:在我的应用程序中,我需要将参数传递给 TimerTask 以供使用 Context
。但我做不到。在下面的代码中GetSMSThread
类是subclass
,需要从主类获取参数。
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 0, 100000);
GetSMSThread
子类:
public class GetSMSThread extends TimerTask
@Override
public void run()
【问题讨论】:
你可以在 MainClass 中声明你的 TimerTask 类本身 【参考方案1】:有两种方法可以解决您的问题
在MainClass
中声明您的GetSMSThread
自己,因此无需在Constructor
中发送参数
另一种方式是在Constructors
中发送参数
选项 1:
public class MainClass extends Activity
private String myString = "";
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
// .... your code
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 0, 100000);
myString = "assigning some value";
public class GetSMSThread extends TimerTask
@Override
public void run()
myString = "manipulating Values";
选项 2:
public class MainClass extends Activity
private String myString = "";
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
// .... your code
myString = "assigning some value";
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread(myString);
smsThread.scheduleAtFixedRate(getSMSThread, 0, 100000);
GetSMSThread:
public class GetSMSThread extends TimerTask
private String myString = "";
public GetSMSThread(String mString)
myString = mString;
@Override
public void run()
myString = "manipulating Values";
【讨论】:
【参考方案2】: Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread("data");
smsThread.scheduleAtFixedRate(getSMSThread, 0, 100000);
GetSMSThread subClass:
public class GetSMSThread extends TimerTask
String data;
GetSMSThread(String data)
this.data = data;
@Override
public void run()
//use data here
【讨论】:
【参考方案3】:您可以通过构造函数将上下文对象传递给类。
public class GetSMSThread extends TimerTask
Context context;
public GetSMSThread (Context context)
this.context = context;
@Override
public void run()
//make sure you dont use the context in a background thread
您可以实例化 **GetSMSThread ** 类并向其传递有效的上下文:
GetSMSThread myThread = new GetSMSThread(myContext);
//start your timer
【讨论】:
以上是关于Android 将参数传递给 TimerTask 扩展类的主要内容,如果未能解决你的问题,请参考以下文章