2014-04-11 16 views
6

第一个问题在这里,但我已经有一段时间了。与前台服务交流android

我有什么:

我建立一个Android应用程序起着音频流和在线播放列表。现在一切正常,但我在与我的服务沟通时遇到问题。

正在播放的音乐的服务,开始与startForeground,所以它不会被杀死。

我需要从我的活动与服务通信,用于获取曲目名称,图像,和一对夫妇的事情更多。

什么我的问题:

我想我要开始我的bindService服务(而不是我目前的startService),这样的活动可以谈论它。

然而,当我这样做,我的服务被关闭活动后死亡。

我该如何得到两者?绑定和前台服务?

谢谢!

+0

您是否尝试过为您的服务制作通知?我认为这应该有助于阻止它被杀害。 – indivisible

+0

我的回答有帮助吗? – Libin

回答

6

bindService将无法​​启动服务。它只会绑定到Serviceservice connection,以便您将有服务的instance访问/控制它。

根据您的要求,我希望您的服务中有MediaPlayer的实例。你也可以从Activity开始服务,然后bind它。如果service已经运行onStartCommand()将被调用,您可以检查是否MediaPlayer实例不为空,然后简单地返回START_STICKY

更改您Activity这样的..

public class MainActivity extends ActionBarActivity { 

    CustomService customService = null; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // start the service, even if already running no problem. 
     startService(new Intent(this, CustomService.class)); 
     // bind to the service. 
     bindService(new Intent(this, 
      CustomService.class), mConnection, Context.BIND_AUTO_CREATE); 
    } 

    private ServiceConnection mConnection = new ServiceConnection() { 
     @Override 
     public void onServiceConnected(ComponentName componentName, IBinder iBinder) { 
      customService = ((CustomService.LocalBinder) iBinder).getInstance(); 
      // now you have the instance of service. 
     } 

     @Override 
     public void onServiceDisconnected(ComponentName componentName) { 
      customService = null; 
     } 
    }; 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     if (customService != null) { 
      // Detach the service connection. 
      unbindService(mConnection); 
     } 
    } 
} 

我有MediaPlayerservice类似的应用程序。让我知道如果这种方法不能帮助你。

+0

在我的情况下,如果我解除我的服务。该服务被杀死。因为绑定它的唯一活动已经关闭/下了视图。这是高度记录。我正在为我的应用做一个下载器系统。但它杀死了服务。当下载程序完成后,我将stopSelf调用到服务中的某个位置,以便我的Service不会永久运行。有任何想法吗? –

2

报价Android documentation

一个绑定的服务被破坏,一旦所有的客户解除绑定,除非该服务也开始

而关于之间的差异开始约束只取一看看https://developer.android.com/guide/components/services.html

所以,你必须使用创建服务然后bindService,就像@利宾在他/她的例子中所做的那样。然后,服务会一直运行,直到您使用stopServicestopSelf或直到Android决定需要资源并杀死您为止。