将值从线程传递到主要活动

Sas*_*ang 2 android

我在网上搜索了很长时间.也许我在这里做的事情是错的.

我在MainActivity.java的单独文件中编写了一个线程类.因为线程和主要活动都相对较长,所以我决定将它们分成不同的文件.

我想将线程类生成的一些值传递给主活动.最初我想使用处理程序.但是因为线程与主要活动属于不同的类.它不知道我在主活动中定义的处理程序.

public class mythread implements Runnable{
    @Override
    public void run(){
        result = result_from_some_task();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的线程类的基本结构,我想将结果传递回主活动.我看了很多例子,其中大多数是主要活动类中的线程,并且可以很容易地引用定义的处理程序.

意图似乎不适用.有没有人知道如何进行这样的操作?

提前致谢.

Uma*_*ari 5

制作AnotherClass的参数化构造函数,当你创建AnotherClass的对象时,只需将MainActivity的对象传递给该构造函数,并在AnotherClass类中调用MainActivity的方法,然后从该Object调用该方法.

检查以下代码:

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 
}
}
Run Code Online (Sandbox Code Playgroud)

并检查另一个类:

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
 }
}
Run Code Online (Sandbox Code Playgroud)