Search code examples
androidfirebasefirebase-realtime-databaseserviceinternet-connection

Firebase: onDisconnect() in a service


I am making a project in which i have to

configure realtime internet connection status

of one client app even if app is in background.

I Have to display it on

ServerSide that weather specific device is connected to internet or not

I am using Firebase to perform this scenerio but it's not working.

ConnectionService

public class ConnectionService extends Service implements ConnectivityReciever.ConnectivityRecieverListner {

    public static final int notify = 5000;
    private Handler mHandler=new Handler();
    private Timer mTimer = null;
    FirebaseDatabase db;
    DatabaseReference dbRef;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        dbRef=FirebaseDatabase.getInstance().getReference(Common.DEVICE_NAME).child("online");
        MyApplication.getInstance().setConnectivtyListner(ConnectionService.this);
        boolean isConnected=ConnectivityReciever.isConnected();
        checkConnection(isConnected);

        if(mTimer!=null){
            mTimer.cancel();
        }else{
            mTimer=new Timer();
            mTimer.scheduleAtFixedRate(new TimeDisplay(),0,notify);
        }
    }

    private void checkConnection(boolean isConnected) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(ConnectionService.this, "Service is destroyed", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onNetworkConnectionChanged(boolean isConnected) {
        if(isConnected){
            dbRef.onDisconnect().setValue("true");
            Toast.makeText(ConnectionService.this, "online", Toast.LENGTH_SHORT).show();

        }
        if(!isConnected){

            dbRef.onDisconnect().setValue(ServerValue.TIMESTAMP);

            Toast.makeText(ConnectionService.this, "offline", Toast.LENGTH_SHORT).show();

        }
    }

    //class TimeDisplay for handling task
    class TimeDisplay extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    MyApplication.getInstance().setConnectivtyListner(ConnectionService.this);
                    boolean isConnected=ConnectivityReciever.isConnected();
                    checkConnection(isConnected);
                    // display toast
                    Toast.makeText(ConnectionService.this, "Service is running", Toast.LENGTH_SHORT).show();
                }
            });

        }

        private void checkConnection(boolean isConnected) {
            if(isConnected){
                dbRef.setValue("true");
                Toast.makeText(ConnectionService.this, "online", Toast.LENGTH_SHORT).show();
            }
            if(!isConnected){

                dbRef.child("online").onDisconnect().setValue(ServerValue.TIMESTAMP);
                Toast.makeText(ConnectionService.this, "offline", Toast.LENGTH_SHORT).show();
            }
        }

    }


}

Applicaiton

public class MyApplication extends Application {
    public static MyApplication mInstance;

    DatabaseReference dbRef;
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance=this;
        Common.DEVICE_NAME = android.os.Build.MODEL;
        FirebaseApp.initializeApp(this);

        FirebaseDatabase.getInstance().setPersistenceEnabled(true);



    }

    public static synchronized MyApplication getInstance(){
        return mInstance;
    }

    public void setConnectivtyListner(ConnectivityReciever.ConnectivityRecieverListner listner){
        ConnectivityReciever.connectivityReceiverListener = listner;
    }
}

I have tried all of methods but nothing worked.

Help will be arreciated.

Thanks


Solution

  • if you have registered your service with menifest.xml & your returning start_sticky, it should work but there's an alternative way also, you can write an api to ping the server(call it in a service after a specific interval), and save the time stamp with TRUE(if isConnected), so now the timestamp is saved along with boolean value true, let's suppose now the connection is OFF or cell is dead, since no updation will be sent to server, right? now it comes the magic of reciver/admin app(where you want to show this online status graphically), now write another API that will fetch that saved response with timestamp & also get the current time when this fetching API will be triggered, find the difference b/w these two time stamps & impose a condition here ` (here difference is in seconds cuz we are using timestamps)

    if(timeDifference>60)`
    {
    echo "true";
    }
    else 
    echo "false";
    

    in this way you can get real time online/offline status on reciver app you ca set

    if(response.equals("true"))
    {
    textView.setText("ONLINE")
    }
    else
    {
    textView.setText("OFFLINE")
    }
    

    further you can read this post answer too Save Response to Server When Network Connection goes OFF