我在使用此代码时会在API 20中丢失连接时收到通知。
registerReceiver(getConnectivityStateBroadcastReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
private class ConnectivityStateBroadcastReceiver extends BaseBroadcastReceiver {
/**
* @param userLoggedIn
* @param context
* @param intent
*/
@Override
protected void onReceive(Boolean userLoggedIn, Context context, Intent intent) {
Bundle extras = intent.getExtras();
boolean notConnected = extras.getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
// DO something
}
}
但它在API 21中无效。
我该如何解决?也许它与ConnectivityManager.NetworkCallbak有关,但我没有找到如何使用它的任何例子。感谢。
答案 0 :(得分:17)
好的,所以我弄清楚如何做到这一点,但我希望确认这个解决方案是正确的。
我所做的只是在我的应用程序类的onCreate中添加对此代码的调用
/**
*
*/
@SuppressLint("NewApi")
private void registerConnectivityNetworkMonitorForAPI21AndUp() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return;
}
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
connectivityManager.registerNetworkCallback(
builder.build(),
new ConnectivityManager.NetworkCallback() {
/**
* @param network
*/
@Override
public void onAvailable(Network network) {
sendBroadcast(
getConnectivityIntent(false)
);
}
/**
* @param network
*/
@Override
public void onLost(Network network) {
sendBroadcast(
getConnectivityIntent(true)
);
}
}
);
}
/**
* @param noConnection
* @return
*/
private Intent getConnectivityIntent(boolean noConnection) {
Intent intent = new Intent();
intent.setAction("mypackage.CONNECTIVITY_CHANGE");
intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, noConnection);
return intent;
}
在已经监控我的API 20连接的IntentFilter中,我添加了这个
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction("mypackage.CONNECTIVITY_CHANGE");
现在我已经在工作的广播接收器也会收到关于API 21中网络变化的通知。
答案 1 :(得分:5)
我会粘贴我的完整解决方案,因为我需要查看很多地方才能使其正常工作:
在应用程序类
中public void onCreate(){
...
IntentFilter filter = new IntentFilter();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Timber.d("using registerNetworkCallback");
createChangeConnectivityMonitor();
filter.addAction(MY_CONNECTIVITY_CHANGE);
} else {
Timber.d("using old broadcast receiver");
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
}
registerReceiver(new SyncOnConnectivityReceiver(), filter);
}
@RequiresApi(Build.VERSION_CODES.N)
private void createChangeConnectivityMonitor() {
final Intent intent = new Intent(MY_CONNECTIVITY_CHANGE);
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
connectivityManager.registerNetworkCallback(
new NetworkRequest.Builder().build(),
new ConnectivityManager.NetworkCallback() {
/**
* @param network
*/
@Override
public void onAvailable(Network network) {
Timber.d("On available network");
sendBroadcast(intent);
}
/**
* @param network
*/
@Override
public void onLost(Network network) {
Timber.d("On not available network");
sendBroadcast(intent);
}
});
}
}
在我的接收器中:
public class SyncOnConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(@Nullable final Context context, Intent intent) {
Timber.d("triggering on connectivity change");
if (context != null && isNetworkAvailable(context)) {
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
syncBusData(context);
}
});
}
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
return false;
}
private void syncData(Context context) {
}
}
在AndroidManifiest.xml中
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<receiver android:name="com.innofied.viapool.location.SyncOnConnectivityReceiver"/>
答案 2 :(得分:0)
如有需要,请尝试
在您的课程中声明必要的变量:
private static final HashMap<Network, Boolean> mNetworkStates = new HashMap<>();
private final Object mSyncNetworkState = new Object();
private Boolean mNetworkState;
定义监视接口更改的方法。如果已连接至少一个网络接口,则mNetworkState始终显示。
private void registerNetworkStateInfo(@NonNull final Context context) throws Exception {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
if (connectivityManager != null) {
connectivityManager.registerNetworkCallback(
builder.build(),
new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
mNetworkStates.put(network, true);
synchronized (mSyncNetworkState){
mNetworkState = true;
}
Log.d("Network state", "Network state: true");
}
@Override
public void onLost(@NonNull Network network) {
mNetworkStates.put(network, false);
synchronized (mSyncNetworkState){
mNetworkState = false;
Log.d("Network state", "Network state: false");
mNetworkStates.forEach(new BiConsumer<Network, Boolean>() {
@Override
public void accept(Network nextNetwork, Boolean state) {
if (state.equals(true)) {
mNetworkState= true;
Log.d("Network state", "Network state: but true");
}
}
});
}
}
}
);
} else {
synchronized (mSyncNetworkState){
mNetworkState = false;
}
throw new Exception("Connectivity Manager is not available");
}
}
使用您的mNetworkState
synchronized (mSyncNetworkState){
if (!mNetworkState) {
throw new Exception("No network available");
}
}