我可以在清单中添加哪些广播接收器?

时间:2012-06-06 13:37:18

标签: android

我希望在设备连接或断开互联网以执行更新时收到通知。我已将此代码放入清单文件中:

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

            </intent-filter>

这是我的Conectivity课程:

package com.funny.pack;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class Conectivity extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {

        Log.w("DHA", "Ceva e diferit la conectivitate");

    }

}

Horewer当设备连接或断开互联网时我没有得到通知我认为这个广播接收器必须只能通过代码来实现吗?是否有可以从清单文件中实现的广播接收器列表,反之亦然?

1 个答案:

答案 0 :(得分:1)

以下代码段将帮助您。

创建一个将处理连接状态通知的BroadcastReceiver

public class MainActivity extends Activity {
    // rest of the code in the Activity are committed for clarity
        private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
            @Override
            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);

                // do application-specific task(s) based on the current network state, such
                // as enabling queuing of HTTP requests when currentNetworkInfo is connected etc.
            }
        };

     registerReceiver(mConnReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    }

包括

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

清单中的