我目前正在研究看似经典的多线程问题(我还在学习多线程)。在我的应用程序中,我通过点击按钮向网站发送请求,然后有一个类,它反复请求网站查看是否每10秒发生一次更改。注意到更改后,UI应该更新。我想确保此过程在单独的线程上完成,以便它不会干扰UI。我尝试过使用ScheduledExecutorService但是我遇到了Runnable线程意识到发生了更改的部分,并且无法返回值以让主进程知道更新UI。我该如何解决这个问题?提前谢谢。
sendPollCmd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!currentModuleInfo.getEngStatus().equals("POLL")){
AlertDialog.Builder builder = new
AlertDialog.Builder(getActivity());
builder.setMessage("Confirm Send Poll Command? This may take a few minutes.").setPositiveButton("Confirm", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mPresenter.commandSequence("POLL", currentModuleInfo.getItemid(), "");
Toast.makeText(getActivity(), "Poll Command sent...Waiting for response", Toast.LENGTH_LONG).show();
mPresenter.checkForUpdate(currentModuleInfo.getItemid(), currentModuleInfo.getEngStatus(), currentModuleInfo.getTime());
}
}).setNegativeButton("Cancel",null);
AlertDialog alert = builder.create();
alert.show();
}
}
});
public void checkForUpdate(String id, String engStatus, String lstMsgTime) {
class Check implements Runnable {
String iden, eng, time;
Check( String id, String engStatus, String lstMsgTime) {
iden = id;
eng = engStatus;
time = lstMsgTime;
}
public void run() {
Module check = getIndividualModule(iden);
System.out.println("------------------------------------");
System.out.println("LOCAL");
System.out.println("engine status: " + eng);
System.out.println("time: " + time);
System.out.println("\n" + "CURRENT");
System.out.println("engine status: " + check.getEngStatus());
System.out.println("time: " + check.getTime());
System.out.println("------------------------------------");
if (!check.getEngStatus().equals(eng) || !check.getTime().equals(time)){
System.out.println("CHANGE DETECTED");
System.out.println("update panel");
return;
}
}
}
ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
executor.scheduleAtFixedRate(new Check(id, engStatus, lstMsgTime), 10, 10, TimeUnit.SECONDS);
}
答案 0 :(得分:0)
有几种方法可以达到这个目的。
看来你的Android也是新手。以下是一些示例Background Service,Receiver to Update UI不建议每隔X秒间隔执行一次网络请求。尝试实施另一种方法。