androidandroid-networking

Accessing object creating in Activity/Fragment from a receiver


This is probably not feasible, but I have a WearOS app that has downloading functionality. According to the documentation, I can request a high-bandwidth network:

https://developer.android.com/training/wearables/data/network-access#requesting-wifi-connectivity

I have all this working however, I also need to release the network when downloading is complete:

Once onAvailable() is called, the device will attempt to remain connected to the Wi-Fi network until the NetworkCallback is released. Release the callback when you no longer need a Wi-Fi network to preserve battery life.

I can release the callback in the Activity/Fragment but I need the connection to stay open until the all downloads are complete. I have a receiver where I check if there are no longer any downloads but, obviously, can't release the callback there.

I thought about using a Singleton but not sure how to create a Singleton for a callback


Solution

  • If you are register receiver from activity,you can create in this receiver interface,and during creation of receiver you can set to receiver your listener,which you will create in activity/fragment. For example:

    class someReceiver extends BroadcastReceiver {
    interface OnLoadComplitionListener {
    void allLoadsCompleted();
    }
    private OnLoadComplitionListener listener;
    public void setOnLoadComplitionListener(OnLoadComplitionListener listener) {
    this.listener =listener;
    }
    @override
    public void OnReceive(Context context) {
    listener.allLoadsCompleted();
    }
    }
    

    And in your activity before registration of your receiver you should set someReceiver.OnLoadComplitionListener and override method allLoadsCompleted(). Name of classes was wrote inexact.