gpt4 book ai didi

java - 连接更改接收器在 android 中获得错误 Intent

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:45:55 26 4
gpt4 key购买 nike

我正在尝试为我的应用添加一些连接状态感知。使用此处的示例和谷歌的文档,我想出了一个接收器,它可以在连接状态更改时正确显示警报,但也会在创建 Activity 时意外地显示警报。

ConnectStatusReceiver:

package com.zivtaller.placefinder.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

public class ConnectStatusReceiver extends BroadcastReceiver {

private String TAG = "netReceiver";

public ConnectStatusReceiver() {
super();
}

@Override
public void onReceive(Context context, Intent arg1) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (isConnected) {
Log.d(TAG, "Data connected");
Toast.makeText(context, "Data connected", Toast.LENGTH_SHORT)
.show();
} else {
Log.d(TAG, "Data not connected");
Toast.makeText(context, "Data not connected", Toast.LENGTH_SHORT)
.show();
}

}

在activity的onResume()中初始化和注册:

        netReceiver = new ConnectStatusReceiver();
IntentFilter netFilter = new IntentFilter();
netFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(netReceiver, netFilter);

最佳答案

系统可能生成粘性广播android.net.conn.CONNECTIVITY_CHANGE intents。粘性广播在发送后仍然存在。每当您注册 BroadcastReceiver 以监听粘性广播时,调用 registerReceiver() 时,最近广播的 Intent 将立即传递给接收器。

测试 android.net.conn.CONNECTIVITY_CHANGE 广播是否有粘性的一种简单方法是检查 registerReceiver() 调用的返回值onResume()

netReceiver = new ConnectStatusReceiver();
IntentFilter netFilter = new IntentFilter();
netFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
Intent intent = registerReceiver(netReceiver, netFilter);
if (intent != null) {
// broadcast is sticky
}

如果您能够确定广播确实具有粘性,那么您遇到的就是预期行为。

参见 what is the difference between sendStickyBroadcast and sendBroadcast in Android .

关于java - 连接更改接收器在 android 中获得错误 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22239889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com