简体   繁体   中英

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?

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

一种选择是将套接字读取器的输出写入流-例如存储在应用程序内部存储中的文件,然后定期在活动线程中轮询该文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM