简体   繁体   English

Android:布尔变化的监听器

[英]Android: Listener for Boolean change

I know that there is a lot of examples, but I can't still make it work.我知道有很多例子,但我仍然无法让它发挥作用。

I need to monitor Boolean value, which change to True, when phone is connected to proper wifi.我需要监视布尔值,当手机连接到正确的 wifi 时,它会更改为 True。 Wifi connection and check is done in second thread. Wifi 连接和检查在第二个线程中完成。 Maybe there is problem?也许有问题? I've tried many solutions, and can't get it done.我尝试了很多解决方案,但无法完成。

Wrapper class for variable:变量的包装类:

import java.util.ArrayList;
import java.util.List;



public class ConnectivityStatus {
    private Boolean status = Boolean.FALSE;
    private ConnectivityListener listener;

    public Boolean getStatus(){
        return status;
    }

    public void setStatus(Boolean status){
        this.status = status;
        if(status) {
            listener.onChange();
        }
    }

    public void addConnectivityListener(ConnectivityListener l) {
        this.listener = l;
    }

    interface ConnectivityListener{
        void onChange();
    }

}

MainActivity:主要活动:

public class MainActivity extends AppCompatActivity {

    ...
    private ConnectivityStatus mConnectionStatus;
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ...
        mConnectionStatus = new ConnectivityStatus();
        ...

        connectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLoadingScreen();
                connectToCamera(mWifiManager);


                new Thread(new Runnable() {
                    public void run() {
                        long startTime = System.currentTimeMillis();
                        for(int i = 0; i<=6; i++) {
                            mConnectionStatus.setStatus(checkWifiSsid(mWifiManager, startTime));
                            if(mConnectionStatus.getStatus()) {
                                break;
                            }
                        }
                    }
                });
            }
        });

        mConnectionStatus.addConnectivityListener(new ConnectivityStatus.ConnectivityListener() {
            @Override
            public void onChange(){
                openWebView();
            }
        });


    }

I didn't notice earlier but, yes, you're missing something from your threading.我之前没有注意到,但是,是的,您在线程中遗漏了一些东西。 You're creating a new thread but you're not telling it to start:您正在创建一个新线程,但没有告诉它开始:

new Thread(new Runnable(){
    public void run(){
        // Optionally, you can also use log messages for debugging
        Log.d("MY_LOG_TAG", "Some message to look for in the log.");

        // ...
    }
}).start(); // Make sure to tell it to start

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM