0

I have a main activity that launches: 1.- A network prone thread that writes into a socket. 2.- A network prone service that is supposed to read from a socket. So far I'm done with 1. but I want the information read from the socket to be shown in the main activity. I know I can pass information between the activity and the service using extras but how can I tell the activity to update and get the new data?

Moises Jimenez
  • 1,962
  • 3
  • 21
  • 43
  • Bind to the service so you can use methods to communicate with each other. http://stackoverflow.com/questions/2274641/best-way-for-service-that-starts-activity-to-communicate-with-it And I would consider putting socket reading and writing into the same service (probably into different threads) so you don't have to communicate with more services than neccessary. – zapl Apr 28 '12 at 17:14

2 Answers2

1

I guess that you could use broadcasting intents combined with a BroadcastReceiver in your main activity in order to achieve background communication.

Here's a snippet that can achieve this.

(CODE PUT IN THE ACTIVITY):

class MyActivity extends Activity{
    CustomEventReceiver mReceiver=new CustomEventReceiver();

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        /*YOUR ONCREATE CODE HERE*/

        /*Set up filters for broadcast receiver so that your reciver
        can only receive what you want it to receive*/
        IntentFilter filter = new IntentFilter();
        filter.addAction(CustomEventReceiver.ACTION_MSG_CUSTOM1);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        registerReceiver(mReceiver, filter);

    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        /*YOUR DESTROY CODE HERE*/
        unregisterReceiver(mReceiver);
    }

    /*YOUR CURRENT ACTIVITY OTHER CODE HERE, WHATEVER IT IS*/

    public class CustomEventReceiver extends BroadcastReceiver{
        public static final String ACTION_MSG_CUSTOM1 = "yourproject.action.MSG_CUSTOM1";
        @Override
        public void onReceive(Context context, Intent intent){
            if(intent.getAction().equals(ACTION_MSG_CUSTOM1)){
                /*Fetch your extras here from the intent
                and update your activity here.
                Everything will be done in the UI thread*/

            }
        }
    }
}

Then, in your service, you simply broadcast an intent (with whatever extras you need)... Say with something like this:

Intent tmpIntent = new Intent();
tmpIntent.setAction(CustomEventReceiver.ACTION_MSG_CUSTOM1);
tmpIntent.setCategory(Intent.CATEGORY_DEFAULT);
/*put your extras here, with tmpIntent.putExtra(..., ...)*/
sendBroadcast(tmpIntent);
epichorns
  • 1,278
  • 8
  • 9
0

One option could be to write the output of the socket reader to a stream - a file stored in the app's internal storage for example, and then periodically poll that file in the activity thread.