Detect CONNECTIVITY CHANGE in Android 7 and above when app is killed/in background

后端 未结 5 1663
礼貌的吻别
礼貌的吻别 2020-11-27 12:56

Problem:

So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other inf

5条回答
  •  Happy的楠姐
    2020-11-27 13:23

    That's how i did it. I have created a IntentService and in onCreate method and I have registered networkBroadacst which check for internet connection.

    public class SyncingIntentService extends IntentService {
        @Override
        public void onCreate() {
            super.onCreate();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                networkBroadcast=new NetworkBroadcast();
                registerReceiver(networkBroadcast,
                      new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
            }
        }
    
        @Override
        public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
            onHandleIntent(intent);
            return START_STICKY;
        }
    }
    

    This is my broadcast class

    public class NetworkBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.isInternetConnected(context)) {
    //            Toast.makeText(context, "Internet Connect", Toast.LENGTH_SHORT).show();
               context.startService(new Intent(context, SyncingIntentService.class));
            }
            else{}
        }
    }
    

    In this way you can check internet connection in whether your app is in foreground or background in nougat.

提交回复
热议问题