如何在点击ListView时使用服务在ExoPlayer上播放特定音频?

huangapple go评论146阅读模式
英文:

How to play particular audio on exoplayer when clicked on listview using service?

问题

AudioPlayerService.javaonCreate方法中,您想要在列表项被点击时告诉服务类播放特定项。您可以考虑使用Intent在活动和服务之间传递数据。但是由于服务类的onCreate方法无法处理意图(Intent),您可以尝试以下方法:

  1. AudioPlayerService.java中创建一个公共方法,用于接受并处理要播放的数据,例如音频文件的URI。然后,从MainActivity中调用此方法,以便在列表项被点击时通知服务类播放特定项。

  2. MainActivity中使用putExtra方法将要播放的数据附加到启动服务的意图中。在服务的onCreate方法中,您可以使用getIntent方法获取包含数据的意图,并从中提取所需的信息来播放特定项。

这两种方法都可以让您在列表项被点击时将数据传递给服务类,并告知它播放特定项。

英文:

I have a following code inside onCreate method of service class AudioPlayerService.java

for (Samples.Sample sample : SAMPLES) {
  MediaSource mediaSource = new ExtractorMediaSource.Factory(cacheDataSourceFactory)
      .createMediaSource(sample.uri);
  concatenatingMediaSource.addMediaSource(mediaSource);
}
player.prepare(concatenatingMediaSource);
player.setPlayWhenReady(true);

This service class is tiggered from MainActivity.

Intent intent = new Intent(this, AudioPlayerService.class);
Util.startForegroundService(this, intent);

And MainActivity class has a listview

ListView listView = findViewById(R.id.list_view);
listView.setAdapter(
    new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, SAMPLES));
listView.setOnItemClickListener(new OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ProgressiveDownloadAction action = new ProgressiveDownloadAction(
        SAMPLES[position].uri, false, null, null);
    AudioDownloadService.startWithAction(
        MainActivity.this,
        AudioDownloadService.class,
        action,
        false);
  }
});

Now i want to tell service class to play particular item of the list to play when item on the list is clicked. I thought of using intent to pass data between activity and service. But i could not communicate effectively because onCreate method of service class does not receive data as it cannot process intent.

Please help. Thanks in advance.

答案1

得分: 0

我通过从调用活动的意图中传递媒体源的位置(在单击时从列表项中获取),在服务的onStartCommand中接收并应用seekTo函数来解决了这个问题:

exoPlayer.seekTo(position, C.TIME_UNSET);

这里的position是从活动传递的整数,并通过意图在服务中接收到。

英文:

I solved it by passing the position of media source, obtained from list item when clicked, through intent from calling activity and receiving inside onStartCommand of service and applying seekTo function as follows:

exoPlayer.seekTo(position, C.TIME_UNSET);

Here position is an integer passed from activity and received on service through the use of intent.

huangapple
  • 本文由 发表于 2020年8月1日 20:34:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63205242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定