0

私には2つの活動があります:

アクティビティ 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)

ラジオが再生されているかどうかを確認し、新しいインスタンスを作成したり、同じラジオを停止して再度再生したりしないようにしたいと考えています。

編集:

リストビュー

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"));
}
4

1 に答える 1

0

私の答えを少し明確にするために:

2 つのオプションがあります (に応じて:

再生中の URL をサービス (onStart 内) に保存し、送信される新しい URL と比較します。

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 を使用して Service を開始し、直接バインドする必要があります。(それ以外の場合、アクティビティが終了した後にサービスが終了します)

于 2012-09-25T14:48:07.523 に答える