2014-05-18 98 views
1

似乎在服务和活动之间交换数据的常用方式是通过处理程序或消息。但是,如果我正在一个活动中启动一个服务,并且我在同一个进程中实现了这个服务,那么为什么我不能访问他们的共享数据,因为它们在相同的地址空间中运行?这是否影响到基本上有两类(活动和服务)?如果没有,如何访问其他数据字段?在服务和活动之间共享数据

如果他们甚至运行在相同的线程(UI)中,同步不再是问题,我只是想知道在这种情况下是否有更简单的方式来共享数据。谢谢。

回答

1

是的,在这种情况下有一个更简单的方法。 建立绑定时,您可以将IBinder转换为您的服务类型。

这里是 http://developer.android.com/reference/android/app/Service.html

private LocalService mBoundService; 

private ServiceConnection mConnection = new ServiceConnection() { 
    public void onServiceConnected(ComponentName className, IBinder service) { 
     // This is called when the connection with the service has been 
     // established, giving us the service object we can use to 
     // interact with the service. Because we have bound to a explicit 
     // service that we know is running in our own process, we can 
     // cast its IBinder to a concrete class and directly access it. 
     mBoundService = ((LocalService.LocalBinder)service).getService(); 

     // Tell the user about this for our demo. 
     Toast.makeText(Binding.this, R.string.local_service_connected, 
       Toast.LENGTH_SHORT).show(); 
    } 
+0

那么如何访问(传递)它们之间的变量? –

+0

你是什么意思?您可以调用服务的方法。 – kupsef

+0

是的,但我的意思是一旦服务中的价值发生变化,我应该能够得到它。像监控服务 –

0

我认为发送意图应该工作。

Intent in = new Intent(youractivity.this,YourService.class); //这里你可以使用 // putExtra方法 startService(in);

在此之后,在该服务中,您可以收到您从该活动发送的值。 我认为这与我们之间的活动相似:) 希望它能起作用。

+0

的培训相关的代码片断,然后如何从服务活动传递价值? –