当我的应用程序从远程服务器获取一些数据时,我需要运行一个函数。 HTTPRequest
需要一些时间来执行,所以当我获得必要的数据时,我发送广播
Intent i = new Intent();
i.setAction(Receiver.BROADCAST_INITIALIZED);
activity.sendBroadcast(i);
我的接收者:
public class Receiver extends BroadcastReceiver{
public static final String BROADCAST_INITIALIZED = "UNIQUE_ID";
public Receiver() {}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BROADCAST_INITIALIZED)) {
Log.i("TAG", "RECEIVER BROADCAST_INITIALIZED");
context.unregisterReceiver(this);
}
}
}
在禁用移动数据和WiFi之前,一切都按预期工作。在这种情况下,activity.sendBroadcast(i);
不会触发。我想知道为什么?
我使用简单的函数来检查连接:
static boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null
&& connectivityManager.getActiveNetworkInfo().isConnected();
}
并将其放入计时器(timer.scheduleAtFixedRate
)。当网络变得可用时,我执行HTTPRequest并获取数据之后我发送广播,即使这样它也不起作用!
sendbroadcast
仅在网络可用时才起作用吗?
更新 我发现了问题。这是我的错。当我注册我的接收器时,我也检查网络可用性,如果它不可用,我只是跳过注册。
if(!Utils.isNetworkAvailable(activity)) return; //The root of my problem!!!
Receiver receiver = new Receiver(new Callable<Void>() {
@Override
public Void call() throws Exception {
func.call();
return null;
}
});
activity.registerReceiver(receiver, new IntentFilter(Receiver.BROADCAST_INITIALIZED));