英文:
How to play particular audio on exoplayer when clicked on listview using service?
问题
在AudioPlayerService.java
的onCreate
方法中,您想要在列表项被点击时告诉服务类播放特定项。您可以考虑使用Intent在活动和服务之间传递数据。但是由于服务类的onCreate
方法无法处理意图(Intent),您可以尝试以下方法:
-
在
AudioPlayerService.java
中创建一个公共方法,用于接受并处理要播放的数据,例如音频文件的URI。然后,从MainActivity
中调用此方法,以便在列表项被点击时通知服务类播放特定项。 -
在
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论