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

无线电.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);
}

服务.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 启动服务,然后直接绑定到它。(否则你的服务在你的活动被杀死后被杀死)

于 2012-09-25T14:48:07.523 回答