将消息或数据从looper传递到主线程

时间:2014-06-10 03:44:54

标签: java android handlers looper

我的应用程序使用广播密码器生成两个包含Loopers ReceiverAccLooper和GetListingsLooper的线程。然后这两个loopers调用一些其他任务来运行,然后将结果返回给Looper。我无法弄清楚如何将结果从loopers返回到主要任务以进一步处理数据。

我尝试过回调和处理程序,我唯一的成功就是使用pool.awaitTermination,但这似乎很草率。我的理解是最好的方法是使用处理程序,但我无法弄清楚如何让一个处理程序从looper发送到主任务。任何有关最佳方法的见解都会非常有用。

... Mainthread

public void onReceive(Context context, Intent intent) {
    Log.d("Plog", "Reciever accounts received alarm");

    DatabaseHandler db = new DatabaseHandler(context);
    List<Contact> contacts = db.getAllContacts();
    Log.d(Plog, "Contacts" + contacts);
    for (Contact cn : contacts) {
        username = cn.getName();
        password = cn.getPassword();
        acb = cn.getBalance();
        strategykey = Integer.parseInt(cn.getStrategy());
        maxamountperautoloan = cn.getMaxperloan();
        int n = 2;
        // Build a fixed number of thread pool
        ExecutorService pool = Executors.newFixedThreadPool(n);

        pool.submit(new ReceiverAccLooper(username, password, acb, maxamountperautoloan, strategykey));

        pool.submit(new GetListingsLooper(username, password, strategykey));

        pool.shutdown();

        //This is where I've been trying to place a handler to get output from the two loopers above

}

其中一个Loopers ....

public class ReceiverAccLooper implements Runnable{
private String username;
private String password;
private String maxamountperloan;
private String acb;
private Integer strategy;
List<Map<String, String>> result;

public ReceiverAccLooper(String _username, String _password, String _acb, String _maxamountperloan, Integer _strategy){
    this.username = _username;
    this.password = _password;
    this.maxamountperloan = _maxamountperloan;
    this.strategy = _strategy;
    this.acb = _acb;
}

@Override
public void run() {
    Looper.prepare();
    Log.d("Plog", "In Looper " + username + " " + password + " " + maxamountperloan + " " + strategy + " " + acb);

    GetLoansReturn glr = new GetLoansReturn();
    glr.GetLoansRunner(username, password, acb, maxamountperloan);
    result = glr.planetsList;
    Log.d("Plog", username + " Looper Result Owned Listings " + result);

    Object msg = result;
    Message sent = (Message) msg;

    //I've would like to send the message from here....

    Looper myLooper = Looper.myLooper();
    Looper.loop();
    myLooper.quit();

}   

}

1 个答案:

答案 0 :(得分:0)

在主线程上使用new-ed处理程序,或者创建指定主线程的Looper。将消息发布或可运行到该处理程序应该这样做。