Search code examples
javaandroidnetwork-programmingservicebackground-process

How to run code in the background continuously - Android


I am having a little bit of a difficulty in managing background services in android. I have this piece of code with me:

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}

I want to run this code in the background and I don't know what I can do. Some people tell me to use Services, but I want this code to be running only in the app, not when the app is closed as well.

I also need the above code, while in the background, to alert the user in the form of a toast when the internet is not there and when it is there.

Can someone please help me? Thanks in advance!


Solution

  • Something like this should do the trick.

    public class MyService extends Service
    {
        @Override
        public int onStartCommand(Intent intent, int flags, int startId)
        {
            //Do something here...
    
            //Check for the connections.
            if(!isNetworkConnected) {
                Toast.makeText(this, "No Internet Connection!", Toast.LENGTH_SHORT).show();
             } else {
                 //Do something else...
             }
    
           //To stop this service. Call it here probably not a right choice. Just as reminder.
            //stopSelfResult(startId);
    
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        private boolean isNetworkConnected() {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
        }
    }