尝试设置上下文,它不是封闭的 class。想法? :)

Trying to set context and it's not an enclosing class. Ideas? :)

我遇到的问题:

有问题的代码(来自 MainActivity)- 第 4 行:

class wifi {
    int signalStrength = 0;
    int loopToggle = 0;
    Context context = MainActivity.this;

    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void loop() throws InterruptedException {
        while (loopToggle == 0) {
            WifiManager signalStrength = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            String wifiInfo = WifiManager.EXTRA_WIFI_INFO;
            TextView textView = (TextView) textView.findViewById(R.id.readOut);
            Thread.sleep(1000);
        }
    }
}

非常感谢您的帮助! :)

这一行 Context context = MainActivity.this; 没有任何意义,除非它在 ​​MainActivity 内,请尝试这样的事情:

@RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void loop(Context context) throws InterruptedException {
        while (loopToggle == 0) {
            WifiManager signalStrength = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            String wifiInfo = WifiManager.EXTRA_WIFI_INFO;
            TextView textView = (TextView) textView.findViewById(R.id.readOut); //this line makes no sence too
            Thread.sleep(1000);
        }
    }

然后从您的 MainActivity 中这样调用它:

loop(MainActivity.this);

希望对您有所帮助

错误是因为您将 wifi 放在 MainActivity class 之外,如下所示:

public class MainActivity extends AppCompatActivity {
  ...
}

class wifi {
  ...
}

wificlass一定要在里面MainActivityclass,像这样:

public class MainActivity extends AppCompatActivity {
  ...

  class wifi {
     ...
  }
}