How to be notified on wifi network status change?

前端 未结 4 1617
醉梦人生
醉梦人生 2020-11-29 02:16

I am writing an app that connects to a telnet server via wifi. I have a service that manages the socket connection. It all works fine, but when the phone sleeps it disconn

相关标签:
4条回答
  • 2020-11-29 03:00

    *set these permissions in your manifest

    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    

    *Register a BroadcastReceiver for these actions filters in your manifest

     <receiver android:name="com.myBroadcastReceiver" >
                <intent-filter>
                    <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
                    <action android:name="android.net.wifi.STATE_CHANGE" />
                </intent-filter>
            </receiver>
    

    *Define your BroadcastReceiver´s implementation

    public class myBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
            WifiManager wifiManager = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
    
            NetworkInfo networkInfo = intent
                    .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (networkInfo != null) {
                Log.d(AppConstants.TAG, "Type : " + networkInfo.getType()
                        + "State : " + networkInfo.getState());
    
    
    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
    
       //get the different network states
    if (networkInfo.getState() == NetworkInfo.State.CONNECTING || networkInfo.getState() ==        NetworkInfo.State.CONNECTED) {
        }
                            }
                          }
    
                        }
                    }
    
    0 讨论(0)
  • 2020-11-29 03:09

    Not sure as to the exact way to do this but I think the ConnectivityManager would be a good place to start.

    http://developer.android.com/reference/android/net/ConnectivityManager.html

    you can get an instance of this class by calling Context.getSystemService(Context.CONNECTIVITY_SERVICE)

    There are also some other good classes in android.net that you can use.

    Hope that helps.

    0 讨论(0)
  • 2020-11-29 03:15

    I know this is an old question but see the following developer documentation:

    http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

    0 讨论(0)
  • 2020-11-29 03:20

    Register a BroadcastReceiver for ConnectivityManager.CONNECTIVITY_ACTION. In the onReceive handler you can call NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO) and then info.getType() and check for ConnectivityManager.TYPE_WIFI and do what you want then. :)

    0 讨论(0)
提交回复
热议问题