在Android SDK中网络事件的意图行动意图、行动、事件、网络

2023-09-11 12:35:44 作者:心痛为谁、不解释

我要接收广播的诸如网络连接,断开连接等网络操作,我使用的是广播接收器用于此目的。谁能告诉我,我需要它的意图动作捕捉的网络事件,现在按我搜索在互联网上我使用的 android.net.ConnectivityManager.CONNECTIVITY_ACTION 。

I need to receive broadcasts for network actions like network connected, disconnected etc. I am using a broadcast receiver for this purpose. Can anyone please tell me which intent action I need to capture for network events, right now as per my search on internet I am using android.net.ConnectivityManager.CONNECTIVITY_ACTION.

下面是我的广播接收器类:

Here is my broadcast receiver class:

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

public class NetworkStateReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub


    if (intent.getAction().equals(
            android.net.ConnectivityManager.CONNECTIVITY_ACTION)) {

        // do something..
    }
}
}

和我还增加了允许访问网络状态:

and I have also added permission for accessing network state:

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

下面就是我已经宣布这个类清单文件

here is how I have declared this class in manifest file

<receiver class=".NetworkStateReceiver" android:name=".NetworkStateReceiver">
    <intent-filter>
            <action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
    </intent-filter>
</receiver>

请给我建议权的意图行动,如果我错了,或者如果有捕捉网络事件的任何其他方式。

Please suggest me the right intent action if I am wrong OR if there is any other way to catch network events.

推荐答案

下面是一个工作的例子:

Here's a working example:

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

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

public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(ConnectivityReceiver.class.getSimpleName(), "action: "
                + intent.getAction());
    }

}