2012-04-28 77 views
0

我有一个主要活动启动: 1.-一个网络容易的线程写入套接字。 2.-应该从套接字读取的网络容易服务。 到目前为止,我已经完成了1个工作,但我希望从主要活动中显示从套接字读取的信息。我知道我可以使用额外功能在活动和服务之间传递信息,但是如何告诉活动更新并获取新数据?Android:我怎样才能告诉某个活动从服务中做些什么?

+0

绑定到服务,以便您可以使用方法相互通信。 http://stackoverflow.com/questions/2274641/best-way-for-service-that-starts-activity-to-communicate-with-it我会考虑把套接字读取和写入到相同的服务(可能不同线程),所以你不必与更多的服务进行通信。 – zapl 2012-04-28 17:14:12

回答

1

我想你可以在你的主要活动中使用与BroadcastReceiver结合的广播意图来实现后台通信。

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

(IN活动代码PUT):

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

是否有任何称为'setCategory()'的意图stil的函数? – 2013-06-25 15:45:51

0

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

相关问题