2013-07-11 19 views
0

我有MP3播放服务,它有自己的类并使用Mediaplayer并与HTTP连接。它必须播放前一个活动中选择的一个URL,并传递给PlayerActivity。将参数传递给Android中正在运行的服务线程

我在PlayerActivity的onCreate创建服务是这样的:

  startService(new Intent(this, PlayerService.class)); 
     Intent connectionIntent = new Intent(this, PlayerService.class); 
     bindService(connectionIntent, mp3PlayerServiceConnection, Context.BIND_AUTO_CREATE); 

这是第一个选择的URL启动。我启动媒体播放器调用在新线程不阻塞UI(呼叫在ActivityPlayer本身):

private ServiceConnection mp3PlayerServiceConnection = new ServiceConnection() { 
    @Override 
    public void onServiceConnected(ComponentName arg0, IBinder binder) { 
     mp3Service = ((LocalBinder) binder).getService(); 


     Thread t = new Thread() { 
     public void run() { 

      mp3Service.playSong(getApplicationContext(),url); 

     } 
     }; 

     t.start(); 


    } 

    @Override 
    public void onServiceDisconnected(ComponentName arg0) { 

    } 
}; 

的问题是如何将一个新的URL传递给该服务的线程,当用户销毁这个活动,去到菜单并选择新的URL。新的流必须在同一个线程中播放,但我有一些情况可以通过后退按钮返回到主页并再次启动应用程序,我同时播放了2个网址。也许是因为新的Thread()声明。因此,当Activity使用URL创建时,如何将其URL传递给Service的线程,因此如果它是旧URL,则什么都不会发生,如果是新的,则播放器切换到新的URL,但不会同时播放2个流?

谢谢。

+0

您是否在bindService或新服务器上返回相同的Binder? –

+0

这里是Service类的代码:'public final IBinder localBinder = new LocalBinder(); @Override public IBinder onBind(Intent intent){ return localBinder; } public class LocalBinder extends Binder {0} {0} PlayerService getService(){ return PlayerService.this; } }' – Tramway11

回答

0

任何不通过广播进行通信的理由?您可以在服务中实施嵌套BroadcastReceiver(并且如果需要在活动中),只需从活动向其发送信号即可。

如果有任何私人数据,您可以使用LocalBroadcastManager来防止系统范围。

编辑:

对于其他用途,还有Android接口定义语言。

+0

也许我已经看到了一些关于这个,但服务通常会首先遇到,所以我选择了更简单的方法(至少对于Android的初学者)... – Tramway11

+0

你可以说一些关于线程在这里使用?是否有2个线程同时出现的可能的越野车位置? – Tramway11

+0

您可以在清单中指定'process =:process_desc'。 ':'将使服务运行在它自己的进程中。 –

相关问题