1

在我的应用程序中,我需要将参数传递给 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() {

    }
}
4

3 回答 3

2

有两种方法可以解决您的问题

  • 声明你GetSMSThread自己,MainClass所以不需要发送参数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);
    }

}

获取短信线程:

public class GetSMSThread extends TimerTask {

    private String myString = "";

    public GetSMSThread(String mString) {
        myString = mString;
    }

    @Override
    public void run() {
        myString = "manipulating Values";
    }
}
于 2014-09-20T07:21:38.457 回答
0
    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
        }
    }
于 2014-09-20T07:12:25.567 回答
0

您可以通过构造函数将上下文对象传递给类。

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
于 2014-09-20T07:23:51.350 回答