简体   繁体   English

动态更新textview数据Android Java

[英]Updating textview data dynamically Android Java

I implemented the code to check wifi state connected or not. 我实现了检查wifi状态是否已连接的代码。 I made a text view 我做了一个文本视图

TextView WifiTv = (TextView) findViewById(R.id.wifistate);

    ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifiCheck = connectionManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);


    if (wifiCheck.isConnected()) {
        // Do whatever here
        WifiTv.setText("WiFi is Connected");
        WifiTv.notify();
    } else {
        WifiTv.setText("WiFi is not Connected");
    }

It works but it does not update dynamically and therefore if I turn off wifi I have to refresh the activity for the textview to change (not data binded). 它可以工作,但不会动态更新,因此,如果我关闭wifi,则必须刷新活动以使textview更改(未绑定数据)。 How can I make the textview update without refresh please? 请问如何在不刷新的情况下更新textview? Thx 谢谢

EDIT: I have this code in a seperate class which works well with a toast. 编辑:我在一个单独的类中有此代码,它与烤面包很好地工作。 All I want to do is display in textview instead. 我要做的只是显示在textview中。 How can I connect the textview variable to this class which does not have xml please? 我如何将textview变量连接到没有xml的此类?

public void onReceive(Context context, Intent intent) {

    NetworkInfo info =
            intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
    if (info != null && info.isConnected()) {
        // Do your work.
        // e.g. To check the Network Name or other info:
        WifiManager wifiManager = (WifiManager)
                context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String ssid = wifiInfo.getSSID();

        Toast.makeText(context, "Connected to: " + ssid,
                Toast.LENGTH_SHORT).show();


    }

You required BroadcastReceiver and wifimanager. 您需要使用BroadcastReceiver和wifimanager。 BroadcastReceiver which start when app launches to receive the the implicit intent every time. 在应用启动时启动的BroadcastReceiver每次都会接收隐式意图。 wifimanager to to check the status. wifimanager来检查状态。

did you try to add a onResume function to check again each time you resume yout activity? 您是否尝试添加onResume函数以在每次恢复活动时再次进行检查?

Don't know your app but maybe this, 不知道您的应用,但也许这

@Override
    protected void onResume() {
        super.onResume();

        if (wifiCheck.isConnected()) {
        // Do whatever here
            WifiTv.setText("WiFi is Connected");
            WifiTv.notify();
        } else {
            WifiTv.setText("WiFi is not Connected");
        }
    }

If your others variables are not global to Activity, create them again within the onResume 如果您的其他变量不是Activity的全局变量,请在onResume中再次创建它们

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

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