我有一个使用以下代码注册观察者的 Activity

Activity :

//Register for network status updates
NetworkStatus networkStatus = new NetworkStatus(this);
networkStatus.addObserver(new OfflineActivity());
Thread thread = new Thread(networkStatus);
thread.run();

学科:
@Override
public void run() {

    for(;;) {
        Log.d("NetworkStatus", "Checking Network Status");
        if(isConnectedToInternet(context)){
            notifyObservers();
            Log.d("NetworkStatus", "Network Connection is established");
        }
        else {
            Log.d("NetworkStatus", "Not connected to network");
        }
    }
}

当我单击该 Activity 时,该程序将变得无响应。。有什么想法吗?

最佳答案

您应该使用.start();

Thread thread = new Thread(networkStatus);
thread.start();
当您显式调用run方法时,它实际上不会产生新的线程,而是该方法调用仍在UI线程中运行。

10-04 12:36