我正试图让Exoplayer播放音频作为后台服务。我正在运行版本2.7.3,所以此功能未像更高版本中那样内置。另外,我使用的是API 21,因此无法进行前台处理。
我所做的是创建一个服务类,该服务类运行我的PlayerActivity,但是不起作用。
服务类别:
public class MyService extends Service {
public MyService() {
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
int id = Objects.requireNonNull(intent.getExtras()).getInt("id");
Intent newIntent = new Intent(this, PlayerActivity.class);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.putExtra("id",id);
startActivity(newIntent);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
我的玩家班级:
public class PlayerActivity extends AppCompatActivity {
ExoPlayer player;
PlayerView playerView;
private long playbackPosition;
private int currentWindow;
private boolean playWhenReady;
BottomNavigationView navigation;
SQLite db = new SQLite(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
playerView = findViewById(R.id.video_view);
playerView.setShowShuffleButton(true);
playerView.setUseArtwork(true);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
// Ensure correct menu item is selected (where the magic happens)
Menu menu = navigation.getMenu();
MenuItem menuItem = menu.getItem(2);
menuItem.setChecked(true);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
startActivity(new Intent(PlayerActivity.this, HomeActivity.class));
return true;
case R.id.navigation_dashboard:
startActivity(new Intent(PlayerActivity.this, SearchDownload.class));
return true;
case R.id.navigation_notifications:
startActivity(new Intent(PlayerActivity.this, PlayerActivity.class));
return true;
}
finish();
return false;
}
};
private void initializePlayer() {
player = ExoPlayerFactory.newSimpleInstance(
new DefaultRenderersFactory(this),
new DefaultTrackSelector(), new DefaultLoadControl());
playerView.setPlayer(player);
player.setPlayWhenReady(playWhenReady);
player.seekTo(currentWindow, playbackPosition);
File yourDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/Capriccio");
String name = "";
int id = Objects.requireNonNull(getIntent().getExtras()).getInt("id");
// if a playlist selected
final ArrayList<PlayListResult> songList = db.GetPlayListSongList(id);
if(songList.size() == 0) {
File[] files = yourDir.listFiles();
for (File f : yourDir.listFiles()) {
if (f.isFile())
name = f.getName();
Toast.makeText(this, name, Toast.LENGTH_LONG).show();
// Do your stuff
}
Uri[] uri = new Uri[files.length];
for (int i = 0; i < files.length; i++) {
uri[i] = Uri.parse(files[i].getAbsolutePath());
}
MediaSource[] mediaSource = buildMediaSource(uri);
MediaSource sources = new ConcatenatingMediaSource(mediaSource);
player.prepare(sources, true, false);
}
else{
Uri[] uri = new Uri[songList.size()];
for (int i = 0; i < songList.size(); i++) {
uri[i] = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
+ songList.get(i).getAbsoluteSongPath$app_debug());
}
MediaSource[] mediaSource = buildMediaSource(uri);
MediaSource sources = new ConcatenatingMediaSource(mediaSource);
player.prepare(sources, true, false);
}
player.addListener(new ExoPlayer.DefaultEventListener() {
@Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections){
int a = player.getCurrentPeriodIndex();
if (songList.size() != 0){
URL url = null;
try {
url = new URL(songList.get(a).getThumbnailUrl$app_debug());
} catch (MalformedURLException e) {
e.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
playerView.setDefaultArtwork(bmp);
String text= "text " + a;
Toast.makeText(PlayerActivity.this,text, Toast.LENGTH_LONG).show();
}
}
@Override
public void onLoadingChanged(boolean isLoading) {
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
}
@Override
public void onRepeatModeChanged(int repeatMode) {
}
@Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
@Override
public void onPlayerError(ExoPlaybackException error) {
}
@Override
public void onPositionDiscontinuity(int reason) {
}
@Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
@Override
public void onSeekProcessed() {
}
});
}
private MediaSource[] buildMediaSource(Uri[] uri) {
MediaSource[] sources = new MediaSource[uri.length];
for(int i = 0; i < uri.length; i++) {
DataSpec dataSpec = new DataSpec(uri[i]);
final FileDataSource fileDataSource = new FileDataSource();
try {
fileDataSource.open(dataSpec);
} catch (FileDataSource.FileDataSourceException e) {
e.printStackTrace();
}
DataSource.Factory factory = new DataSource.Factory() {
@Override
public DataSource createDataSource() {
return fileDataSource;
}
};
sources[i] = new ExtractorMediaSource(fileDataSource.getUri(),
factory, new DefaultExtractorsFactory(), null, null);
}
return sources;
}
@Override
public void onStart() {
super.onStart();
if (Util.SDK_INT > 23) {
initializePlayer();
}
}
@Override
public void onResume() {
super.onResume();
hideSystemUi();
if ((Util.SDK_INT <= 23 || player == null)) {
initializePlayer();
}
}
@SuppressLint("InlinedApi")
private void hideSystemUi() {
playerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
@Override
public void onPause() {
super.onPause();
if (Util.SDK_INT <= 23) {
releasePlayer();
}
}
@Override
public void onStop() {
super.onStop();
if (Util.SDK_INT > 23) {
releasePlayer();
}
}
private void releasePlayer() {
if (player != null) {
playbackPosition = player.getCurrentPosition();
currentWindow = player.getCurrentWindowIndex();
playWhenReady = player.getPlayWhenReady();
player.release();
player = null;
}
}
}
我确实希望这样做能够达到目的,因为我希望活动可以作为服务运行,但是我想我应该尝试仅将部分播放器放入服务中,尽管不确定哪个以及如何。< / p>