java将消息或数据从活套传递到主线程
我的应用程序使用了一个广播接收器,它产生了两个线程,其中包含Looper ReceiverAccLooper和GetListingsLooper。这两个循环器然后调用一些其他任务来运行,然后将结果返回给循环器。我不知道如何将活套的结果返回到主任务以进一步处理数据
我尝试过回调和处理程序,唯一的成功就是使用了pool。但这似乎有些草率。我的理解是,最好的方法是使用处理程序,但我不知道如何让处理程序从活套发送到主任务。任何关于实现这一点的最佳方法的见解都将非常有用
主线程
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
}
其中一个活套
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 楼答案
在主线程上使用新的处理程序,或者指定主线程的循环器来创建处理程序。将消息或runnable发布到该处理程序应该可以做到这一点