0

我有一个启动的主要活动: 1.- 写入套接字的网络易发线程。2.-应该从套接字读取的网络易发服务。到目前为止,我已经完成了 1。但我希望从套接字读取的信息显示在主要活动中。我知道我可以使用 extras 在活动和服务之间传递信息,但我如何告诉活动更新并获取新数据?

4

2 回答 2

1

我想你可以在你的主要活动中使用广播意图和广播接收器来实现后台通信。

这是一个可以实现这一点的片段。

(活动中的代码):

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*/

            }
        }
    }
}

然后,在您的服务中,您只需广播一个意图(以及您需要的任何额外内容)......用这样的话说:

Intent tmpIntent = new Intent();
tmpIntent.setAction(CustomEventReceiver.ACTION_MSG_CUSTOM1);
tmpIntent.setCategory(Intent.CATEGORY_DEFAULT);
/*put your extras here, with tmpIntent.putExtra(..., ...)*/
sendBroadcast(tmpIntent);
于 2012-04-28T17:11:11.230 回答
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.

于 2012-04-28T17:47:40.103 回答