В этом уроке будут рассмотрены следующие темы:
• Запуск нового activity;
• Передача дополнительной информации в activity при запуске;
• Получение информации об аудиофайле по id;
• Проигрывание музыки;
• Обработка нажатия на кнопку.
Intent startIntent = new Intent (this, PlayActivity.class);
startActivity(startIntent);
startIntent.putExtra("id", id);
Intent intent = getIntent();
long id = intent.getLongExtra("id", -1);
private Uri uri;
if (id != -1) {
uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(uri, null, null, null, null);
cursor.moveToFirst();
TextView albumView = (TextView) findViewById(R.id.album);
int albumColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
String album = cursor.getString(albumColumn);
albumView.setText(album);
cursor.close();
mediaPlayer = new MediaPlayer();
private boolean prepare() {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getApplicationContext(), uri);
mediaPlayer.prepare();
} catch (Exception e) {
return false;
}
return true;
}
private boolean prepare() {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
state = State.NOT_VALID;
try {
mediaPlayer.setDataSource(getApplicationContext(), uri);
mediaPlayer.prepare();
state = State.STOPPED;
} catch (Exception e) {
return false;
}
return true;
}
private boolean play() {
try {
mediaPlayer.start();
state = State.PLAYING;
} catch (IllegalStateException e) {
state = State.NOT_VALID;
return false;
}
return true;
}
private boolean stop() {
try {
mediaPlayer.stop();
state = State.STOPPED;
} catch (IllegalStateException e) {
state = State.NOT_VALID;
return false;
}
return true;
}
private boolean pause() {
try {
mediaPlayer.pause();
state = State.PAUSED;
} catch (IllegalStateException e) {
state = State.NOT_VALID;
return false;
}
return true;
}
private void release() {
mediaPlayer.release();
}
@Override
protected void onStart() {
if (prepare())
play();
super.onStart();
}
@Override
protected void onStop() {
stop();
release();
super.onStop();
}
private OnCompletionListener completionListener = new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer listener) {
state = State.STOPPED;
}
};
mediaPlayer.setOnCompletionListener(completionListener);
private OnClickListener playButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (state == State.PLAYING)
pause();
else if (state == State.STOPPED || state == State.PAUSED)
play();
}
};
playButton = (ImageButton) findViewById(R.id.playButton);
playButton.setOnClickListener(playButtonListener);
playButton.setImageResource(android.R.drawable.ic_media_pause);
playButton.setImageResource(android.R.drawable.ic_media_play);
Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 1