2013-07-11 17 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'。 ':'將使服務運行在它自己的進程中。 –

相關問題