Android - 检查我正在播放的收音机

时间:2012-09-25 10:52:41

标签: android service android-activity radio

我有两项活动:

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

1 个答案:

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