我是android的初学者,我在internet.xml中添加了2个图标
  ,基于网络连接(例如是否已连接网络)
  应显示已连接图标,否则应显示未连接图标
  在工具栏上),为此我在以下位置创建了onPrepareOptionsMenu()
  活动以及BroadcastReceiver来广播当前网络
  状态,因为图标必须动态更改。
  
  在这里我使用了Intent来广播当前的网络状态,它是
  再次重新启动活动,我不知道该如何打电话
  BroadcastReceiver类中的onPrepareOptionsMenu()
  根据网络自动更新工具栏中的菜单项
  状态。
  
  谁能帮助我做到这一点?


**ConnectionActivity**

public class ConnectionActivity extends AppCompatActivity {
        Menu menu;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_parser);
        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.internet, menu);
            return super.onCreateOptionsMenu(menu);
        }

        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            boolean online = false;
            MenuItem netMenuItem = menu.findItem(R.id.network_signal);
            MenuItem nonetMenuItem = menu.findItem(R.id.network_signal_off);
            int status = NetworkUtil.getConnectivityStatus(this);
            if (status == 1 || status == 2)
                online = true;
            else
                online = false;
            netMenuItem.setVisible(online);
            nonetMenuItem.setVisible(!online);

            return true;
        }

    }

**NetworkUtil.java**


            public class NetworkUtil {
            public static int TYPE_WIFI = 1;
            public static int TYPE_MOBILE = 2;
            public static int TYPE_NOT_CONNECTED = 0;


            public static int getConnectivityStatus(Context context) {
                ConnectivityManager cm = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                if (null != activeNetwork) {
                    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                        Log.d("WIFI CONNECTED", activeNetwork.getType() + "");
                        return TYPE_WIFI;
                    }
                    if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                        Log.d("MOBILE CONNECTED", activeNetwork.getType() + "");
                        return TYPE_MOBILE;
                    }
                }
                Log.d("NOT CONNECTED", TYPE_NOT_CONNECTED + "");
                return TYPE_NOT_CONNECTED;
            }

            public static String getConnectivityStatusString(Context context) {
                int conn = NetworkUtil.getConnectivityStatus(context);
                String status = null;
                if (conn == NetworkUtil.TYPE_WIFI) {
                    status = "Wifi enabled";
                } else if (conn == NetworkUtil.TYPE_MOBILE) {
                    status = "Mobile data enabled";
                } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
                    status = "Not connected to Internet";
                }
                return status;
            }
        }

**NetworkChangeReceiver**


            public class NetworkChangeReceiver extends BroadcastReceiver {

            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onReceive(Context context, Intent intent) {
                String status = NetworkUtil.getConnectivityStatusString(context);
                Toast.makeText(context, status, Toast.LENGTH_LONG).show();
               Intent activityIntent = new Intent(context, ParserActivity.class);
                activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(activityIntent);
            }
        }

 **Menifest.xml**

     <receiver
            android:name=".NetworkChangeReceiver"
            android:enabled="true"
            android:exported="false">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>

**internet.xml**


         <?xml version="1.0" encoding="utf-8"?>
        <menu xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto">
            <item
                android:title="signal_off"
                android:id="@+id/network_signal_off"
                android:icon="@drawable/ic_signal_wifi_off_black_24dp"
                app:showAsAction="always"></item>
            <item
                android:id="@+id/network_signal"
                android:icon="@drawable/ic_signal_wifi_4_bar_black_24dp"
                android:title="Signal"
                app:showAsAction="always"></item>
        </menu>

最佳答案

还有另一种方法,而不是通过调用onPrepareOptionsMenu

public class NetworkChangeReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    if (isOnline(context)) {
                        // show online icon
                        ConnectionActivity.setMenuVisible(true);
                    } else {
                       // show offline icon
                        ConnectionActivity.setMenuVisible(false);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            private boolean isOnline(Context context) {
                try {
                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getActiveNetworkInfo();
                    //should check null because in airplane mode it will be null
                    return (netInfo != null && netInfo.isConnected());
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }


================================================== ==========================

public class ConnectionActivity extends AppCompatActivity {
        Menu menu;
        private BroadcastReceiver mNetworkReceiver;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_parser);
            mNetworkReceiver = new NetworkChangeReceiver();
            registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }

        @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.internet, menu);
    this.menu = menu;
    this.menu.findItem(R.id.network_signal).setVisible(false);
    this.menu.findItem(R.id.network_signal_off).setVisible(false);
    return super.onCreateOptionsMenu(menu);
}

        public static void setMenuVisible(boolean isOnline) {
            if (isOnline) {
                if (menu != null) {
                    menu.findItem(R.id.network_signal).setVisible(true);
                    menu.findItem(R.id.network_signal_off).setVisible(false);
                }
            } else {
                if (menu != null) {
                    menu.findItem(R.id.network_signal_off).setVisible(true);
                    menu.findItem(R.id.network_signal).setVisible(false);
                }
            }
        }

        private void unregisterNetworkChanges() {
            try {
                unregisterReceiver(mNetworkReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            unregisterNetworkChanges();
        }
    }

09-30 21:13