2012-09-25 55 views
0

我有2個活動:的Android - 檢查收音機我打

活動A - 列表視圖/適配器

活動B - 無線電

在活動A,我選擇的無線電和B劇本那個無線電(服務)。

但是每當我在列表中選擇另一臺收音機時,活動B就會再次進行,電臺將停止並再次播放。

情況例如:

# 1 - I'm playing Radio X, I choose X on the list 
# 2 - A new instance is created (service is in onCreate() of Activity B) 
# 3 - Radio X playing (play() is in onStart() of service) 
# 4 - I go back to the list 
# 5 - I want to play Radio Y 
# 6 - A new instance is created (service is in onCreate() of Activity B) 
# 7 - Radio Y playing (play() is in onStart() of service) 
# * In onCreate() of service isn't doing nothing 

一切都很好,但如果我回到列表,選擇相同的無線電,會發生什麼情況,例如:

# 1 - Radio Y playing 
# 2 - I go back to the list 
# 3 - I wanna go to Radio Y again 
# 4 - A new instance is created (service is in onCreate() of Activity B) (I don't want this) 
# 5 - Radio Y stops and plays again (I don't want this) 

我想有一種檢查收音機是否播放的方式與我想要的收音機相同,並且不要創建新的實例,也不要停下來再播放同一收音機。

編輯:

的ListView

if (item == "Radio 1"){ 
     Intent intent = new Intent(getBaseContext(), Radio.class); 
     intent.putExtra("radio", "http://test1.com"); 
     this.startActivity(intent); 
} else if (item == "Radio 2"){ 
     Intent intent = new Intent(getBaseContext(), Radio.class); 
     intent.putExtra("radio", "http://test2.com"); 
     this.startActivity(intent); 
} 

Radio.java

@Override 
public void onCreate(Bundle icicle) { 
    requestWindowFeature(Window.FEATURE_LEFT_ICON); 
    super.onCreate(icicle); 
    setContentView(R.layout.main); 

    Intent music = new Intent(getApplicationContext(), Service.class); 
    music.putExtra("url", this.getIntent().getStringExtra("radio")); 
    startService(music); 
} 

Service.java

@Override 
public void onStart(Intent intent, int startid) { 
    Multiplayer m = new MultiPlayer(); 
    m.playAsync(intent.getExtras().getString("url")); 
} 

回答

0

爲了澄清我的回答有點:

您有2個選項(具體取決於:

將播放的網址存儲在服務(onStart)中,並將其與正在發送的新網址進行比較。

private String mCurrentUrl; 

@Override 
public void onStart(Intent intent, int startid) {  
    String newUrl = intent.getExtras().getString("url"); 

    if ((newUrl.equals(mCurrentUrl)) { 
     mCurrentUrl = newUrl; 
     Multiplayer m = new MultiPlayer(); 
     m.playAsync(mCurrentUrl); 
    } 
} 

或:

定義以檢索當前無線電信道的服務(AIDL)的接口。如果讓活動綁定到它,則可以調用此方法來檢索當前頻道。注意:您必須使用startService啓動服務,然後直接綁定到它。 (否則你的服務在你的Activity被殺後死亡)

+0

謝謝!但我仍然不明白這段代碼會如何幫助我。這段代碼將會看到一個實例是否已經存在,那麼我可以在這個代碼中驗證新的流媒體鏈接是否是同一個服務流媒體鏈接,如果沒有,停止收音機並從新鏈接開始,是嗎? – Felipe

+0

我編輯了我的問題,我沒有使用綁定,這是一個簡單的服務。像我這樣,總是創建一個Radio的新實例,總是進入Radio的onCreate()方法,並且總是進入Service的onStart()方法。我想要一個簡單的方法:/ – Felipe

+0

如果服務已經運行,服務將不會被重新創建。因此,如果您檢查當前網址到服務的onStart中的新網址,您可以選擇不做任何事情。 – RvdK