Search code examples
androidsocketsserviceandroid-activityextras

Android: How can I tell an activity to do something from a service?


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?


Solution

  • 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);