在我的Android应用程序中,我有一个MainActivity类,它启动一个Thread。这个线程做了Stuff并在屏幕上显示它。 (这部分正在运作)
从线程我想访问MainActivity-Class中的方法。但它不起作用......"无法解决方法"
这是我的代码......
线程对象:
public class SensorProcessor implements Runnable {
protected Context mContext;
protected Activity mActivity;
private volatile boolean running = true;
//Tag for Logging
private final String LOG_TAG = SensorProcessor.class.getSimpleName();
public SensorProcessor(Context mContext, Activity mActivity){
this.mContext = mContext;
this.mActivity = mActivity;
}
public void run() {
while (running){
try {
final String raw = getSensorValue();
mActivity.runOnUiThread(new Runnable() {
public void run() {
//WORKS
final TextView textfield_sensor_value;
textfield_sensor_value = (TextView) mActivity.findViewById(R.id.text_sensor);
textfield_sensor_value.setText("Sensor Value: " + raw);
Log.v(LOG_TAG, raw);
//DOES NOT WORK, WHY?
mActivity.myMethod(); //Cannot resolve method
}
});
Thread.sleep(100);
} catch (InterruptedException e) {
//When an interrupt is called, we set running to false, so the thread can exit nicely
running = false;
}
}
Log.v(LOG_TAG, "Sensor Thread finished");
}
}
MainActivity类,调用线程:
public class MainActivity extends Activity implements OnClickListener, OnInitListener {
public void myMethod(){
//Do stuff...
}
//Start the Thread, when the button is clicked
public void onClick(View v) {
if (v.getId() == R.id.button_start) {
runnable = new SensorProcessor(this.getApplicationContext(),this);
thread = new Thread(runnable);
thread.start();
}
}
}
为什么它不起作用,使用mActivity.runOnUiThread(new Runnable() - Approach,以及如何正确完成?
祝你好运
答案 0 :(得分:1)
使用mActivity
类型MainActivity
输入((MainActivity)mActivity)
。但请确保您不应该从线程更新UI。
答案 1 :(得分:1)
你需要使用一个Handler才能在线程和ui-thread(你的活动)之间进行交互所以这就是我要做的。
public class SensorProcessor implements Runnable {
protected Context mContext;
protected Handler handler;
private volatile boolean running = true;
//Tag for Logging
private final String LOG_TAG = SensorProcessor.class.getSimpleName();
// here I pass a handler instead of activity
public SensorProcessor(Context mContext, Handler handler){
this.mContext = mContext;
this.handler = handler;
}
// here is the key. Replace mActivity.myMethod(); with the following
handler.sendEmptyMessage(randomIntegerNumberWhatever);
...etc etc
然后创建一个像dat一样的自定义处理程序
public class MessageHandler extends Handler
{
public interface IHandler
{
void myMethod();
}
private final IHandler activityHandler;
public MessageHandler(IHandler listener)
{
activityHandler = listener;
}
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
if (msg.what == randomIntegerNumberWhatever)
{
activityHandler.myMethod();
}
}
}
然后让您的活动实现MessageHandler.IHandler接口。它可能看起来很复杂,但它可以信任我
答案 2 :(得分:0)
myMethod()
类中不存在 Activity
,因此强制转换为(或提供)MainActivity
答案 3 :(得分:0)
Activity
类不包含myMethod()
函数。
您需要将数据类型更改为具有此功能的特定活动:
protected MainActivity mActivity;
public SensorProcessor(Context mContext, MainActivity mActivity){
this.mContext = mContext;
this.mActivity = mActivity;
}