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

后端 未结 5 1657
礼貌的吻别
礼貌的吻别 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条回答
  •  一整个雨季
    2020-11-27 13:10

    Nougat and Above: We have to use JobScheduler and JobService for Connection Changes.

    All I can divide this into three steps.

    Register JobScheduler inside activity. Also, Start JobService( Service to handle callbacks from the JobScheduler. Requests scheduled with the JobScheduler ultimately land on this service's "onStartJob" method.)

    public class NetworkConnectionActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_network_connection);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            scheduleJob();
    
        }
    
    
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        private void scheduleJob() {
            JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
                    .setRequiresCharging(true)
                    .setMinimumLatency(1000)
                    .setOverrideDeadline(2000)
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                    .setPersisted(true)
                    .build();
    
            JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
            jobScheduler.schedule(myJob);
        }
    
        @Override
        protected void onStop() {
            // A service can be "started" and/or "bound". In this case, it's "started" by this Activity
            // and "bound" to the JobScheduler (also called "Scheduled" by the JobScheduler). This call
            // to stopService() won't prevent scheduled jobs to be processed. However, failing
            // to call stopService() would keep it alive indefinitely.
            stopService(new Intent(this, NetworkSchedulerService.class));
            super.onStop();
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            // Start service and provide it a way to communicate with this class.
            Intent startServiceIntent = new Intent(this, NetworkSchedulerService.class);
            startService(startServiceIntent);
        }
    }
    

    The service to start and finish the job.

    public class NetworkSchedulerService extends JobService implements
            ConnectivityReceiver.ConnectivityReceiverListener {
    
        private static final String TAG = NetworkSchedulerService.class.getSimpleName();
    
        private ConnectivityReceiver mConnectivityReceiver;
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.i(TAG, "Service created");
            mConnectivityReceiver = new ConnectivityReceiver(this);
        }
    
    
    
        /**
         * When the app's NetworkConnectionActivity is created, it starts this service. This is so that the
         * activity and this service can communicate back and forth. See "setUiCallback()"
         */
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i(TAG, "onStartCommand");
            return START_NOT_STICKY;
        }
    
    
        @Override
        public boolean onStartJob(JobParameters params) {
            Log.i(TAG, "onStartJob" + mConnectivityReceiver);
            registerReceiver(mConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
            return true;
        }
    
        @Override
        public boolean onStopJob(JobParameters params) {
            Log.i(TAG, "onStopJob");
            unregisterReceiver(mConnectivityReceiver);
            return true;
        }
    
        @Override
        public void onNetworkConnectionChanged(boolean isConnected) {
            String message = isConnected ? "Good! Connected to Internet" : "Sorry! Not connected to internet";
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    
        }
    }
    

    Finally, The receiver class which checks the network connection changes.

    public class ConnectivityReceiver extends BroadcastReceiver {
    
        private ConnectivityReceiverListener mConnectivityReceiverListener;
    
        ConnectivityReceiver(ConnectivityReceiverListener listener) {
            mConnectivityReceiverListener = listener;
        }
    
    
        @Override
        public void onReceive(Context context, Intent intent) {
            mConnectivityReceiverListener.onNetworkConnectionChanged(isConnected(context));
    
        }
    
        public static boolean isConnected(Context context) {
            ConnectivityManager cm = (ConnectivityManager)
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        }
    
        public interface ConnectivityReceiverListener {
            void onNetworkConnectionChanged(boolean isConnected);
        }
    }
    

    Don't forget to add permission and service inside manifest file.

    
    
    
        
        
    
    
        
        
        
        
        
        
    
        
            
                
                    
    
                    
                
            
    
    
            
            
        
    
    
    

    Please refer below links for more info.

    https://github.com/jiteshmohite/Android-Network-Connectivity

    https://github.com/evant/JobSchedulerCompat

    https://github.com/googlesamples/android-JobScheduler

    https://medium.com/@iiro.krankka/its-time-to-kiss-goodbye-to-your-implicit-broadcastreceivers-eefafd9f4f8a

提交回复
热议问题