BroadcastReceiver Wifi禁用

时间:2013-10-15 17:33:20

标签: java android broadcastreceiver android-broadcast

我希望我的应用程序在wifi离线时发出通知'离线'

我想出了通知部分。但我似乎无法弄清楚' wifi检查&-39; -part。 我读了一些关于BroadcastReceiver的内容,但我似乎无法让它工作。任何有用的链接?还是示例代码?教程?

提前致谢!

已更新代码。它工作但我需要它只在wifi下线时发出通知。

    public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {        

    super.onCreate(savedInstanceState);  
    this.registerReceiver(this.mConnReceiver,
            new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    setContentView(R.layout.activity_main);
}

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
        boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

        NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

        if(currentNetworkInfo.isConnected()){

        }else{
            showNotification();
        }
    }
};

1 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情

In Manifest.xml
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

In your application Code:

public class BroadCastSampleActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.registerReceiver(this.mConnReceiver,
            new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
        boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

        NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

        if(currentNetworkInfo.isConnected()){
            Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
        }
    }
};
}