0

I have a service class that I want to use to check for internet both when app is closed and in the background. If app is online a method will be called from within service class This is the code for the service

public class MyService extends Service {
    public MyService() {
    }
    NotificationCompat.Builder builder;
    private FirebaseAuth.AuthStateListener mAuthListener;


    static final String CONNECTIVITY_CHANGE_ACTION="android.net.conn.CONNECTIVITY_CHANGE";


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
        // throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public int onStartCommand(Intent intent,int flags,int startId) {
        Toast.makeText(getApplicationContext(), "checking for new bookings", Toast.LENGTH_SHORT).show();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (CONNECTIVITY_CHANGE_ACTION.equals(action)) {
                    if (!ConnectionHelper.isConnectedOrConnecting(context)) {
                        if (context != null) {
                            boolean show = false;
                            if (ConnectionHelper.lastNoConnectionTs == -1) {
                                show = true;
                                ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
                            } else {
                                if (System.currentTimeMillis() - ConnectionHelper.lastNoConnectionTs > 1000) {
                                    show = true;
                                    ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
                                }
                            }
                            if (show && ConnectionHelper.isOnline) {
                                ConnectionHelper.isOnline = false;
                                Log.i("NETWORK123", "Connection lost");
                            }
                        }
                    } else {
                        Log.i("NETWORK123", "Connection lost");
                        ConnectionHelper.isOnline = true;
                        Methodwhenappisonline();
                    }
                }
            }
        };

        registerReceiver(receiver,filter);
        return START_STICKY;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        Toast.makeText(getApplicationContext(),"service killed",Toast.LENGTH_SHORT).show();
    }
}

Below is my connection helper class

public class ConnectionHelper {
    public static long lastNoConnectionTs=-1;
    public static boolean isOnline=true;
    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnected();
    }
    public static boolean isConnectedOrConnecting(Context context){
        ConnectivityManager cm=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork=cm.getActiveNetworkInfo();
        return activeNetwork!=null&&activeNetwork.isConnectedOrConnecting();
        // activeNetwork.isConnectedOrConnecting();
    }
}

And below is my manifest

 <service 
  android:name=". MyService" 
  android:enabled="true" 
  android:exported=true></service>

The service is to run wehh the app is in background and when it is closed. However when the app is in the background it is destroyed after some time and when it is closed it is destroyed instantly. Please help. Please note my minimum sdk version is 16.

Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
Yayayaya
  • 216
  • 3
  • 13
  • 2
    Does this answer your question? [Background service for android oreo](https://stackoverflow.com/questions/47110489/background-service-for-android-oreo) – Pawel Nov 10 '19 at 16:04
  • No it doesn't, my minimum api level is 16 – Yayayaya Nov 10 '19 at 16:14
  • Minimum API level does not determine how your app behaves - it's based mostly on target sdk level with some exceptions. Background service limit is one of them. Also API 16 is almost legacy at this point. Unless it's a project for personal use you have to optimize your app for current API. – Pawel Nov 10 '19 at 16:30
  • I know, but the call startforegroundservice is for api 26 and above – Yayayaya Nov 10 '19 at 16:37
  • Your code snippet does not include your service calling [`startForeground(int, Notification)`](https://developer.android.com/reference/android/app/Service#startForeground(int,%20android.app.Notification)) which has to be used within 5 seconds of starting the service to display sticky notification and satisfy foreground contract. – Pawel Nov 10 '19 at 16:41
  • So I just add that? – Yayayaya Nov 10 '19 at 17:20

0 Answers0