当前位置: 动力学知识库 > 问答 > 编程问答 >

android - Pass value from thread to main activity

问题描述:

I've been searching this online for a long time. Maybe what I'm doing here is wrong.

I have written a thread class in a separate file from MainActivity.java. Because both the thread and the main activity are relatively long, I decided to separate them into different files.

I wanted to pass some value generated from the thread class to the main activity. Initially I want to use handlers. But because the thread is in a different class to the main activity. It has no idea the handler I defined in the main activity.

public class mythread implements Runnable{

@Override

public void run(){

result = result_from_some_task();

}

}

This is the basic structure of my thread class and I want to pass result back to the main activity. I've looked at many examples, most of them the thread is within the main activity class and the handlers defined can be easily referred to.

Intent doesn't seems to be applicable. Does anyone have any idea on how such operations can be done?

Thanks in advance.

网友答案:

Make parameterized constructor of AnotherClass and when you make of object of AnotherClass then simply pass object of MainActivity into that constructor and inside AnotherClass class where you want to call MainActivity's method then simply call that method from that Object.

check following code :

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AnotherClass object= new AnotherClass (this);
    object.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void makeSomeCalculation() {
    //logic to change some UI 
}
}

and check Another class :

public class AnotherClass extends Thread {

MainActivity mainActivity;

public AnotherClass (MainActivity mainActivity) {
    // TODO Auto-generated constructor stub

    this.mainActivity = mainActivity;
}

public void run() {
   //write other logic
        mainActivity.makeSomeCalculation();
   //write other logic
 }
}
网友答案:

This may not be what you are looking for so consider it as suggestion to avoid long term headaches.Try EventBus. This a library to communicate easily between various components in Android.

网友答案:

you need a handler in your activity. and when your thread finishes , you then dispatch a message to handler , notifying that thread execution finished. see here for example. you can also use interface for this. see here for example. In answer, he use interface to notify from asyntask. you can do same for thread.

分享给朋友:
您可能感兴趣的文章:
随机阅读: