-1

What is the best practice for transfer of some (not huge, but often) amount of data from several services to activity?

I'm using BroadcastReceiver in my MainActivity this way:

private class Receiver extends BroadcastReceiver{
    public Receiver() {
        super();
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        // Receiving and showing received symbols
        if (intent.getAction() == getString(R.string.key_recognized)) {
            char key = intent.getCharExtra("key" , '0');                
            MainActivity.this.addText(key); 
        }

        // Received transfer ending flag
        if (intent.getAction() == getString(R.string.transfer_ended)) {
            mServiceWorking = false;
            MainActivity.this.mToneButton.setText(getText(R.string.send_text)); 
        }

        // Recieving an array (~2Kb) and drawing it on correspondig ImageView
        if (intent.getAction() == getString(R.string.spectrum_ready)) {
            Spectrum spectrum = (Spectrum) intent.getSerializableExtra("spectrum");
            if (spectrum != null) {
                drawSpectrum(spectrum);
            }
        }
    }

}

Broadcasts are sended from services somehow like this:

Intent taskIntent = new Intent();     
taskIntent.setAction(getString(R.string.key_recognized));
taskIntent.putExtra("key", key);
this.sendBroadcast(taskIntent);

Is this normal code or my hands should be cut off in some way?)

Sovan
  • 168
  • 1
  • 3
  • 12

3 Answers3

1

I don't see why passing the data via extras is not the best choice. For me, is the safest, and fastest way to pass data between activities or intents.

pamobo0609
  • 812
  • 10
  • 21
0

You can simple use post method from Handler class

Illya Bublyk
  • 712
  • 6
  • 21
-1

For normal data up to a maximum of 1MB (see this answer) you can use extra data of intents.

For bigger data, or data that is not serializable, you could store that data in one of following:

  • In a file. Pass URI in extra data.
  • In the shared preferences.
  • In a special class that holds your data. Store it in a hashmap, where you pass the key in your extra data of the intent.

The class could look like this:

private static final Map<Long, Object> storage = new HashMap<>();

public static synchronized long store(Object tempData){
    if(storage.size() < Long.MAX_VALUE) {
        storage.put(storage.size() + 1l, tempData);
        return storage.size();
    }else{
        return -1;
    }
}

The store()-Method returns a long value, that can be used to identify the stored data. This way is faster than storing your data in a file and can be bigger than 1MB. But keep in mind, that you have limited memory in android, so don't store to many or too big data. Remove them as soon as you retrieved them.

Community
  • 1
  • 1
AlbAtNf
  • 3,859
  • 3
  • 25
  • 29