getBoolean(EXTRA_NO_CONNECTIVITY) 始终返回 false

发布于 2024-12-02 00:52:56 字数 2219 浏览 1 评论 0原文

有一次我遇到了一个问题,你们真的很有帮助。所以在这里我又遇到了另一个问题... :/

我正在运行一个扩展 BroadcastReceiver 的自定义 NetworkReceiver。我想检测手机何时有互联网连接,以便我可以随时启动服务。我已经阅读了很多主题,并且所有主题或多或少都会提示以下代码,这对我不起作用:

public class NetworkReceiver extends BroadcastReceiver {

private static final String tag = NetworkReceiver.class.getSimpleName();

@Override
public void onReceive(Context context, Intent intent) {
    Log.i(tag,"****** NetworkReceiver // onReceive()");

    boolean noConnection = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

    if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        Log.i(tag,"****** NetworkReceiver // Network Down?: " + intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false));
    }

    // TODO Bug: Never stops the service. Stays always connected!
    if(noConnection) {
        Log.i(tag,"****** NetworkReceiver // Stopping Service...");
        context.stopService(new Intent(context, FetchService.class));
    } else {
        Log.i(tag,"****** NetworkReceiver // Starting Service!");
        context.startService(new Intent(context, FetchService.class));
    }
}

我遇到的问题是 logcat 总是返回 NetworkDown?: false 并且该服务从不返回停止(它总是重新启动)。我通过按 F8 在模拟器上进行了尝试,并且还通过关闭路由器在我的开发手机上进行了尝试(它没有 SIM 卡,互联网访问是通过我的 wifi 路由器进行的) ->不保证互联网接入!

我的清单包括以下几行:

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

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

我还应该注意到我也尝试过 我的清单文件中的 没有任何更改,当我更改该行时: intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true) 结果总是正确的 - 因此它总是试图停止我的服务并且从不启动它。

我怀疑 Intent 中的 Extras 根本没有被读取,这就是为什么 getBooleanExtra() 总是返回默认值的原因。

PS。我使用的是 Android 2.1

谢谢!

One time that I had a prob, you guys were really helpful. So here I am again with another problem I have fallen onto... :/

I am running a custom NetworkReceiver that extends BroadcastReceiver. I want to detect when the phone has an internet connection so that I can start a service whenever it does. I have read a lot of topics and all topics more or less prompt to the following code which DOES NOT WORK for me:

public class NetworkReceiver extends BroadcastReceiver {

private static final String tag = NetworkReceiver.class.getSimpleName();

@Override
public void onReceive(Context context, Intent intent) {
    Log.i(tag,"****** NetworkReceiver // onReceive()");

    boolean noConnection = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

    if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        Log.i(tag,"****** NetworkReceiver // Network Down?: " + intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false));
    }

    // TODO Bug: Never stops the service. Stays always connected!
    if(noConnection) {
        Log.i(tag,"****** NetworkReceiver // Stopping Service...");
        context.stopService(new Intent(context, FetchService.class));
    } else {
        Log.i(tag,"****** NetworkReceiver // Starting Service!");
        context.startService(new Intent(context, FetchService.class));
    }
}

The problem I have is that the logcat always returns NetworkDown?: false and the service never stops (it restarts all the time). I tried it on the emulator by pressing F8 and I also tried it on my dev-phone (it has no SIM, internet access is by my wifi router) by switching off the router -> no internet access guaranteed!

My Manifest includes the following lines:

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

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

I should also note that I also tried
<action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" /> in my manifest file with no change and that when I altered the line:
intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
to
intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true)
the result was always true - and thus it always tried to stop my service and never start it.

I suspect that the Extras from the Intent are not read at all and that is why the default value of getBooleanExtra() always returns.

PS. I am on Android 2.1

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

裂开嘴轻声笑有多痛 2024-12-09 00:52:56

我不确定 BroadcastReceiver 内无法读取的附加内容,但我可以向您展示我使用 BroadcastReceiver 实现与您类似的目的的方式。

我的接收器仅捕获连接变化,但不评估连接状态。相反,它会通知Service,因为在两种情况下(无论是否连接)该服务都会有一些事情要做。该服务当时可以运行也可以不运行,因此它将启动或“通知”(请记住 您可以安全地多次调用 startService(),这些调用不会嵌套):

public class ConnectivityReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final Intent intentService = new Intent(context, MyService.class);
        intentService.putExtra(MyService.INTENT_HANDLE_CONNECTIVITY_CHANGE, "");

        context.startService(intentService);
    }
}

然后,在我的服务中,我会评估连接性,然后采取行动因此。请注意,我不会像您一样评估连接状态,这可能就是为什么下面的代码有效但不是您的代码(下面仅是相关代码):

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        final Bundle bundle = intent.getExtras();

        // Handle the intent INTENT_HANDLE_CONNECTIVITY_CHANGEif any
        if ((bundle != null) && (bundle.get(INTENT_HANDLE_CONNECTIVITY_CHANGE) != null)) {         
            handleConnectivity(); 
        }
    }

    return START_STICKY;
}

private void handleConnectivity() {
    final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if(netInfo != null && netInfo.isConnected()) {
        // WE ARE CONNECTED: DO SOMETHING
    }   
    else {
        // WE ARE NOT: DO SOMETHING ELSE    
    }
}

这工作正常,在 Android-7 (2.1) 下为出色地。

I am not sure for the Extras that cannot be read inside the BroadcastReceiver, but I can show you athe way I use the BroadcastReceiver for a purpose similar to yours.

My receiver does only catch the connectivity changes, but it does NOT evaluate the connectivity status. It informs the Service instead as in both cases (connected or not) this service will have something to do. This service can be running or not at that time, so it will either be started or "informed" (remember that you can safely call startService() several times, these calls do not nest):

public class ConnectivityReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final Intent intentService = new Intent(context, MyService.class);
        intentService.putExtra(MyService.INTENT_HANDLE_CONNECTIVITY_CHANGE, "");

        context.startService(intentService);
    }
}

Then, in my service, I do evaluate the connectivity and then act accordingly. Notice that I don't evaluate the connection status the same way as you do, and this might be why the code below works but not yours (below is the relevant code only):

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        final Bundle bundle = intent.getExtras();

        // Handle the intent INTENT_HANDLE_CONNECTIVITY_CHANGEif any
        if ((bundle != null) && (bundle.get(INTENT_HANDLE_CONNECTIVITY_CHANGE) != null)) {         
            handleConnectivity(); 
        }
    }

    return START_STICKY;
}

private void handleConnectivity() {
    final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if(netInfo != null && netInfo.isConnected()) {
        // WE ARE CONNECTED: DO SOMETHING
    }   
    else {
        // WE ARE NOT: DO SOMETHING ELSE    
    }
}

This works fine, under Android-7 (2.1) as well.

゛时过境迁 2024-12-09 00:52:56

不知道奇怪的 NO_CONNECTIVITY 标志,但您可以从意图中检索活动网络:

(NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

您可能只需在此对象上调用 isConnected() 即可。

Don't know about the strange NO_CONNECTIVITY flag, but you can retrieve the active network from the intent:

(NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

You can probably just call isConnected() on this object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文