0

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

我想通了通知部分。但我似乎无法弄清楚“wifi检查”部分。我读了一些关于 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();
        }
    }
};
4

1 回答 1

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();
        }
    }
};
}
于 2013-10-15T17:40:28.013 回答