[android] Wifi Connect-Disconnect Listener



1 Answers

创建自己的类,扩展BroadcastReceiver ...

public class MyNetworkMonitor extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // Process the Intent here

    }
}

在AndroidManifest.xml中

<receiver
    android:name=".MyNetworkMonitor" >
        <intent-filter>
            <action android:name="android.net.wifi.STATE_CHANGE" />
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
</receiver>

有关使用Intent的说明,请参阅WIFI_STATE_CHANGED_ACTIONCONNECTIVITY_ACTION

Question

我的班级必须实施哪个监听器,以便在wifi连接/断开连接时自动检查代码?

我能够手动检查wifi连接/断开,但每次我需要连接/断开Android设置的WIFI,然后运行我的程序的结果。

我目前的代码很简单:

WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()==true)
{
    tv.setText("You are connected");
}
else
{
    tv.setText("You are NOT connected");
}



AndroidManifest.xml中添加以下权限。

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

创建新的Receiver类。

public class ConnectionChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetInfo != null
            && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            Toast.makeText(context, "Wifi Connected!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "Wifi Not Connected!", Toast.LENGTH_SHORT).show();
        }
    }

并将该接收器类添加到AndroidManifest.xml文件中。

<receiver android:name="ConnectionChangeReceiver"
          android:label="NetworkConnection">
  <intent-filter>
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
  </intent-filter>
</receiver>





Related