Android Best way to keep and share data through the app

I am making a small Android app that run a Foreground Service which listen and notify the user whenever a new SMS message arrived. When the Service start it register the BroadcastReceiver with action android.provider.Telephony.SMS_RECEIVED in IntentFilter, and unregister it when stop. The application also get the user data along with a list of selected number from a JSON file in internal storage so that the Receiver can filter out which number to notify the user. My MainActivity has 3 buttons, Start and Stop Service, along with a Setting button that move to SettingActivity that display some user info as well as the list of selected number and allow the user to change it. My question is that: What is the best way to share the user data throughout the app so that all Activity as well as Service and Receiver can access it? I have thought of and tried a few ways:

So what is the right way to implement this? Please give me some suggestion. Thank you guys in advance.

Upvotes: 0

Views: 69

Answers (1)

lhdev
lhdev

Reputation: 11

There are a few suggestions for this:

1 - You could store the data you need in shared preferences, though if this is personal data, that you'd want to keep private (eg passwords, personally identifiable information) you probably don't want to do this.

2 - Similarly to what you are doing in your activity, you could create a service which is responsible for getting the user data from the file and keeps hold of it until the app is killed, for example -

public class UserDataStore()

This way you can create an instance of a UserDataStore on startup and then, through dependency injection, pass it around your app. So wherever you create your service that handles the broadcast events, you can just add a UserDataStore as a parameter, assuming you create your UserDataStore first. eg -

public class BroadcastReceiverService(UserDataStore store)

This way also means that your BroadcastReceiverService is more testable as you can mock the UserDataStore.

Example -

public class MainActivity() {

    UserDataStore store = new UserDataStore()

    BroadcastReceiverService broadcastService = new BroadcastReceiverService(store)

}

Then in your UserDataStore -

public class UserDataStore() {

// in here you want to get all your info about the user eg username, email etc

    String name = ""

    init {
        User user = getUserInfo()
        name = user.name
    }


    public String getUserName() {
       return name
    }  

}

Then finally in your broadcast receiver

public class BroadcastReceiverService(UserDataStore store) {

    public void receiveMessage(Message msg) {
        if(msg.username == store.name) // continue
    }

}

Upvotes: 1

Related Questions