【发布时间】:2018-09-26 20:44:15
【问题描述】:
我目前正在解决似乎是经典的多线程问题(我仍在学习多线程)。在我的应用程序中,我通过单击按钮向网站发送请求,然后有一个类重复请求网站查看是否每 10 秒发生一次更改。一旦注意到更改,UI 应该会更新。我想确保这个过程是在一个单独的线程上完成的,这样它就不会干扰 UI。我曾尝试使用 ScheduledExecutorService,但是我被困在 Runnable 线程意识到发生更改并且无法返回值以让主进程知道更新 UI 的部分。我将如何解决这个问题?提前致谢。
UI_FragmentClass.java
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();
}
}
});
presenterClass.java
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);
}
【问题讨论】:
标签: android multithreading concurrency