Android equivalent to NSNotificationCenter

前端 未结 8 2064
旧时难觅i
旧时难觅i 2020-12-22 15:35

In the process of porting an iPhone application over to android, I am looking for the best way to communicate within the app. Intents seem to be the way to go, is this the b

8条回答
  •  北海茫月
    2020-12-22 16:25

    You could use weak references.

    This way you could manage the memory yourself and add and remove observers as you please.

    When you addObserver add these parameters - cast that context from the activity you are adding it in to the empty interface, add a notification name, and call the method to run interface.

    The method to run interface would have a function that is called run to return the data that you are passing something like this

    public static interface Themethodtorun {
            void run(String notification_name, Object additional_data);
        }
    

    Create a observation class that invokes a reference with a empty interface. Also construct your Themethodtorun interface from the context being passed in the addobserver.

    Add the observation to a data structure.

    To call it would be the same method however all you need to do is find the specific notification name in the data structure, use the Themethodtorun.run(notification_name, data).

    This will send a callback to where ever you created an observer with a specific notification name. Dont forget to remove them when your done!

    This is good reference for weak references.

    http://learningviacode.blogspot.co.nz/2014/02/weak-references-in-java.html

    I am in the process of uploading this code to github. Keep eyes open!

提交回复
热议问题