在单独的线程检测到对象状态

时间:2018-04-17 01:53:28

标签: android multithreading concurrency

我目前正在研究看似经典的多线程问题(我还在学习多线程)。在我的应用程序中,我通过点击按钮向网站发送请求,然后有一个类,它反复请求网站查看是否每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);

}

1 个答案:

答案 0 :(得分:0)

有几种方法可以达到这个目的。

  1. 创建将检查网站更新的后台服务
  2. 如果发现更新,则发送广播接收器以通知UI填充更新。
  3. 看来你的Android也是新手。以下是一些示例Background ServiceReceiver to Update UI不建议每隔X秒间隔执行一次网络请求。尝试实施另一种方法。