I'm working on an app that consist in two activity one that is the media player and the other one that is the list of song to play, the mp3 player is working fine, from the activity with the list i'm passing the name of the song and player works fine. I have two problems, if the user plays a song and leaves the app(the song keeps playing in the background, which is how is suppose to work) then the user return to the app, the seekbar bar is set to 0 and the timer to 0, is there a way to "save" the activity"...also is if one song is playing and the user tries to play another song, the song play on top of the previous song, I try to fix this by adding into my intent a "key" to identifies if is is a new audio and then do something like this: but is not working.
if (playerL != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop;
}
}
public class AudioPlayer extends Activity {
/////////////////////////////////////////////////////////////
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player_activity);
// Header
Bundle extra = getIntent().getExtras();
if (extra != null) {
Intent intent = getIntent();
id_d = intent.getStringExtra("Id");
heading = intent.getStringExtra("Heading");
fileN = intent.getStringExtra("fileName");
audioN = intent.getStringExtra("audioName");
playerL = intent.getStringExtra("newAudio");
meet_instructor_round_image = findViewById(R.id.audio_player_img);
playerHeading = findViewById(R.id.audio_player_heading);
playerHeading.setText(heading);
Picasso.with(this).load(imgUrl).transform(new CropCircleTransformation()).into(round_image);
createNotificationChannel();
activateNotification(id_d, heading, imgUrl, bio);
} else {
Intent intent = new Intent(getApplicationContext(), com.starvizn.newstarvizn.COMMON.Activities.MainActivity.class);
startActivity(intent);
}
pause = findViewById(R.id.btnAudioSubpause);
play = findViewById(R.id.btnAudioSubPlay);
songName = findViewById(R.id.workoutName);
initialTime = findViewById(R.id.initialTime);
songName.setText(audioN);
Uri uri = Uri.parse(getApplicationContext().getFilesDir()+"/Downloads/"+fileN+".mp3");
mediaPlayer = MediaPlayer.create(this, uri);
seekBar = findViewById(R.id.seekBar);
seekBar.setClickable(false);
pause.setVisibility(View.INVISIBLE);
// Open lesson view
lessons_layout = findViewById(R.id.player_lessons);
lessons_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "Aqui");
Intent intent = new Intent(getApplicationContext(), com.myApp.MainActivity.class);
intent.putExtra("Id", id_d);
startActivity(intent);
}
});
if (playerL != null) {
if (mediaPlayer.isPlaying()) {
}
}
}
public void player_play(View view) {
play.setVisibility(View.INVISIBLE);
pause.setVisibility(View.VISIBLE);
mediaPlayer.start();
finalTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();
if (oneTimeOnly == 0) {
seekBar.setMax((int) finalTime);
oneTimeOnly = 1;
}
initialTime.setText(String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime)))
);
seekBar.setProgress((int) startTime);
myHandler.postDelayed(UpdateSongTime, 100);
seekBar.setClickable(false);
pause.setVisibility(View.VISIBLE);
}
public void player_pause(View view) {
pause.setVisibility(View.INVISIBLE);
play.setVisibility(View.VISIBLE);
int temp = (int) startTime;
mediaPlayer.pause();
}
public void player_fwd(View view) {
int temp = (int) startTime;
if ((temp + fwdTime) <= finalTime) {
startTime = startTime + fwdTime;
mediaPlayer.seekTo((int) startTime);
} else {
Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds!", Toast.LENGTH_LONG).show();
}
}
public void player_back(View view) {
int temp = (int) startTime;
if ((temp - backTime) > 0) {
startTime = startTime - backTime;
mediaPlayer.seekTo((int) startTime);
} else {
Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_LONG).show();
}
}
private Runnable UpdateSongTime = new Runnable() {
public void run() {
startTime = mediaPlayer.getCurrentPosition();
initialTime.setText(String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
toMinutes((long) startTime)))
);
seekBar.setProgress((int) startTime);
myHandler.postDelayed(this, 100);
}
};
#Override
public void onBackPressed() {
builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("End Player").setMessage("Exit").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancelAll();
Intent intent = new Intent(getApplicationContext(), com.myapp.MainActivity.class);
intent.putExtra("Id", id_d);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
}
So I guess you just need to add the logic which suppose to handle that process. As documentation says you have two methods
getCurrentPosition() and seekTo(long, int)
So I think you suppose to save current position for example in prefs and resume with help of seekTo method with that data which you saved before. So with help of that you could manage states
When I was working on player app I used ExoPlayer it is more flexible and easier to use. You can try the link below
https://codelabs.developers.google.com/codelabs/exoplayer-intro/#0
Related
i m making a quiz app , in my quizzActivity where qestions load i used countDowntimer so when this countdown timer is finished i m displaying alert dialog of Game over with sound , everything working fine
Problem is when my quiz is finished , i am also getting the Gameover sound in my result activity , and in MainActivity.
my QuizzActvity code
ActivityQuizBinding binding;
ArrayList<Questions> qestions;
Questions question;
CountDownTimer timer;
FirebaseFirestore database;
int correctAnswer = 0;
MediaPlayer mMediaPlayer;
int index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityQuizBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
qestions = new ArrayList<>();
database = FirebaseFirestore.getInstance();
final String cateGoryID = getIntent().getStringExtra("categoryID");
database.collection("categories")
.document(cateGoryID)
.collection("questions")
.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (DocumentSnapshot snapshot : queryDocumentSnapshots) {
Questions questions = snapshot.toObject(Questions.class);
qestions.add(questions);
}
Collections.shuffle(qestions);
setNextQestions();
}
});
resetTimer();
}
void resetTimer() {
timer = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long l) {
binding.timer.setText(String.valueOf(l / 1000));
}
#Override
public void onFinish() {
new AlertDialog.Builder(QuizActivity.this)
.setIcon(R.drawable.sad)
.setTitle("Oops Game Over!")
.setCancelable(false)
.setMessage(" Please Try Again ")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Intent in = new Intent(QuizActivity.this, MainActivity.class);
startActivity(in);
finish();
}
}).create().show();
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(QuizActivity.this, R.raw.wrong);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(false);
mMediaPlayer.start();
}
};
}
public void CheckAnwer(TextView textView) {
String selectAnswer = textView.getText().toString();
if (selectAnswer.equals(question.getAnswer())) {
correctAnswer++;
textView.setBackground(getResources().getDrawable(R.drawable.option_right));
} else {
showAnswer();
textView.setBackground(getResources().getDrawable(R.drawable.option_wrong));
}
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(QuizActivity.this)
.setIcon(R.drawable.ic_baseline_person_24)
.setMessage("Are you sure want to Quit Game")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent in = new Intent(QuizActivity.this, MainActivity.class);
startActivity(in);
finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create().show();
}
public void setNextQestions() {
if (timer != null) {
timer.cancel();
}
timer.start();
if (index < qestions.size()) {
binding.qestioncounter.setText(String.format("%d/%d", (index + 1), qestions.size()));
question = qestions.get(index);
binding.qestions.setText(question.getQestion());
binding.option1.setText(question.getOption1());
binding.option2.setText(question.getOption2());
binding.option3.setText(question.getOption3());
binding.option4.setText(question.getOption4());
index++;
} else {
reset();
Toast.makeText(this, "Quiz Finsished", Toast.LENGTH_SHORT).show();
Intent in = new Intent(QuizActivity.this, ResultActivity.class);
in.putExtra("correct_answer", correctAnswer);
in.putExtra("total", qestions.size());
startActivity(in);
}
}
void reset() {
binding.option1.setBackground(getResources().getDrawable(R.drawable.option_unselected));
binding.option2.setBackground(getResources().getDrawable(R.drawable.option_unselected));
binding.option3.setBackground(getResources().getDrawable(R.drawable.option_unselected));
binding.option4.setBackground(getResources().getDrawable(R.drawable.option_unselected));
}
void showAnswer() {
if (question.getAnswer().equals(binding.option1.getText().toString()))
binding.option1.setBackground(getResources().getDrawable(R.drawable.option_right));
else if (question.getAnswer().equals(binding.option2.getText().toString()))
binding.option2.setBackground(getResources().getDrawable(R.drawable.option_right));
else if (question.getAnswer().equals(binding.option3.getText().toString()))
binding.option3.setBackground(getResources().getDrawable(R.drawable.option_right));
else if (question.getAnswer().equals(binding.option4.getText().toString()))
binding.option4.setBackground(getResources().getDrawable(R.drawable.option_right));
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.option_1:
case R.id.option_2:
case R.id.option_3:
case R.id.option_4:
if (timer != null) {
timer.cancel();
}
TextView selected = (TextView) view;
CheckAnwer(selected);
break;
case R.id.next_btn:
reset();
setNextQestions();
break;
}
}
}
You have to stop the MediaPlayer before switching to another activity. You may use the OnActivityResult result for stopping Mediaplayer while switching between activities.
Here is the sample code:
public static final int REQUEST_CODE = 1;
Intent in = new Intent(QuizActivity.this, MainActivity.class);
startActivityForResult(in, REQUEST_CODE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
mMediaPlayer.stop()
}
} catch (Exception ex) {
}
}
Also, make sure that you cancel the CountDownTimer before switching to another activity.
I am trying to make a countdown timer screen that will keep counting down if I back out of the app or change screens or something. For some reason it keeps crashing saying that timeLeft is null. I can't figure out why it would be because I know the time variable in my Countdown class is there. Thanks for any help!
Countdown Activity
public class Countdown extends Activity {
public static String time;
public static String address;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
Intent confIntent = getIntent();
time = confIntent.getStringExtra("time");
address = confIntent.getStringExtra("address");
LocalBroadcastManager.getInstance(this).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView textView= findViewById(R.id.t1);
String timeLeftString = intent.getStringExtra("timeSent");
int timeLeft = Integer.parseInt(timeLeftString);
if(timeLeft>0) {
textView.setText("You have " + timeLeft + " minutes left");
}
else{
textView.setText("Y'all outta time, see ya again soon!");
killIt();
}
}
}, new IntentFilter(CountdownService.ACTION_LOCATION_BROADCAST)
);
Intent toService = new Intent(this, CountdownService.class);
startService(toService);
}
#Override
protected void onResume() {
super.onResume();
TextView textView= findViewById(R.id.t1);
textView.setText("You have " + CountdownService.toSend + " minutes left");
}
#Override
protected void onPause() {
super.onPause();
}
public void killIt(){
stopService(new Intent(this, CountdownService.class));
}
}
Countdown Service
public class CountdownService extends Service{
public static int toSend=0;
public int time;
public static final String
ACTION_LOCATION_BROADCAST = CountdownService.class.getName() +
"LocationBroadcast";
public final String timeFromCD = Countdown.time;
public final String address = Countdown.address;
#Override
public void onCreate() {
super.onCreate();
time = Integer.parseInt(timeFromCD);
time = time*60000;
new CountDownTimer(time, 5000) {
public void onTick(long millisUntilFinished) {
int timeLeftInt = (int) Math.ceil((double) millisUntilFinished / 60000); //Whole number of minutes left, ceiling
sendBroadcastMessage(timeLeftInt);
toSend = timeLeftInt;
if(timeLeftInt == 5){
Notify("Not Done");
}
}
public void onFinish() {
sendBroadcastMessage(0);
Notify("done");
Response.Listener<String> response = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//creating a jsonResponse that will receive the php json
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(CountdownService.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
SpotAmountRequest spotAmountRequest = new SpotAmountRequest(address, "0", response);
RequestQueue queue = Volley.newRequestQueue(CountdownService.this);
queue.add(spotAmountRequest);
}
}.start();
}
private void sendBroadcastMessage(int timeSent) {
Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
intent.putExtra("timeSent", timeSent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void Notify(String doneness){
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, Map.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
if(doneness.equals("done")) {
Notification n = new Notification.Builder(this)
.setContentTitle("Time to leave!")
.setContentText("Your PrePark spot has expired, time to go home!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(0, n);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(1000);
}
else{
Notification n = new Notification.Builder(this)
.setContentTitle("Ya got 5 minutes left in your PrePark spot!")
.setContentText("Better get going soon here")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(0, n);
}
}
}
You're storing an int value in the intent that you're broadcasting from the service, but you're then trying to get it out as a String where you receive the broadcast. Either change the receiver to use getIntExtra instead of getStringExtra, or convert the int to a String in the service before storing it in the intent.
public class GameActivity extends AppCompatActivity {
TextView txtTurn, txtScore, txtQuestion, txtQuestionNumber, txtTimer;
Button[] btnAnswers;
Player players[];
ArrayList<Question> questions;
Question currentQuestion;
CountDownTimer gameTime;
Boolean answered, timesup;
int score, turn, round;
final int TIMES = 11000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
txtTurn = (TextView)findViewById(R.id.txtTurnGame);
txtScore = (TextView)findViewById(R.id.txtScoreGame);
txtTimer = (TextView)findViewById(R.id.txtTimer);
txtQuestionNumber = (TextView)findViewById(R.id.questionNumber);
txtQuestion = (TextView)findViewById(R.id.txtQuestion);
btnAnswers = new Button[4];
btnAnswers[0] = (Button)findViewById(R.id.answer1);
btnAnswers[1] = (Button)findViewById(R.id.answer2);
btnAnswers[2] = (Button)findViewById(R.id.answer3);
btnAnswers[3] = (Button)findViewById(R.id.answer4);
answered = false;
timesup = false;
Intent intent = getIntent();
players = MainActivity.players;
turn = intent.getExtras().getInt("turn");
score = players[turn].getScore();
round = intent.getExtras().getInt("round");
questions = MainActivity.shuffledQuestionList;
currentQuestion = questions.get(round/2);
Integer[] randomAnswer = new Integer[4];
for (int i = 0; i < randomAnswer.length; i++) {
randomAnswer[i] = i;
}
Collections.shuffle(Arrays.asList(randomAnswer));
txtTurn.setText(TurnActivity.txtTurn1.getText());
txtScore.setText("Score : " + Integer.toString(score));
txtQuestion.setText(currentQuestion.getQuestion());
txtQuestionNumber.setText("QUESTION #" + Integer.toString(round/2+1));
for (int i = 0; i < randomAnswer.length; i++){
String[] answers = currentQuestion.getAnswersList();
btnAnswers[i].setText(answers[randomAnswer[i]]);
}
gameTime = new CountDownTimer(TIMES, 1000){
public void onTick(long millisUntilFinished) {
if(!timesup)
txtTimer.setText("Time : " + millisUntilFinished / 1000 + "s");
}
public void onFinish() {
txtTimer.setText("Time's Up");
timesup = true;
finishTurn();
}
};
gameTime.start();
}
public void answerChoose(View v){
if(!answered && !timesup){
answered = true;
gameTime.cancel();
Button btnPressed = ((Button) v);
if(btnPressed.getText().equals(currentQuestion.getAnswer())){
btnPressed.setBackgroundColor(Color.GREEN);
players[turn].setScore(score+1);
}
else{
btnPressed.setBackgroundColor(Color.RED);
}
finishTurn();
}
}
private void finishTurn(){
gameTime.cancel();
if(round+1 >= 10){
final Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
startActivity(intent);
finish();
}
else {
final Intent intent = new Intent(getApplicationContext(), TurnActivity.class);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//Toast.makeText(getApplicationContext(), "Player2 Time!", Toast.LENGTH_SHORT).show();
intent.putExtra("turn", turn);
intent.putExtra("round", round + 1);
startActivity(intent);
finish();
}
}.start();
}
}
So, I try to make a quiz game. There are 4 buttons as answer choices. When user click a(any) button, it refer to answerChoose method which stops the timer and make an intent to TurnActivity (finishTurn method). The timer displayed as a TextView and of course it stopped, the TextView not changed anymore (seems like the timer stopped)
public void answerChoose(View v){
if(!answered && !timesup){
answered = true;
gameTime.cancel();
Button btnPressed = ((Button) v);
//Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
if(btnPressed.getText().equals(currentQuestion.getAnswer())){
btnPressed.setBackgroundColor(Color.GREEN);
players[turn].setScore(score+1);
}
else{
btnPressed.setBackgroundColor(Color.RED);
}
finishTurn();
}
}
But something happen really weird, after reached the TurnActivity, the timer doesn't seem to stop, the timer keeps running until reach the end and make a new intent to TurnActivity (once again). As you can see I called finishTurn method in onFinish method of CountDownTimer. So, the timer itself not stopped even the cancel method declared in answerChoose method.
gameTime = new CountDownTimer(TIMES, 1000){
public void onTick(long millisUntilFinished) {
if(!timesup)
txtTimer.setText("Time : " + millisUntilFinished / 1000 + "s");
}
public void onFinish() {
txtTimer.setText("Time's Up");
timesup = true;
finishTurn();
}
};
Problem solved. All I have to do is override the onStop method.
#Override
protected void onStop() {
super.onStop();
gameTime.cancel();
}
I've created a simple music player in Android which has a seekbar which displays the current position in the song playing. The forward, rewind, play and pause functions work correctly. What I am trying to do is have the seekbar actually move the position within the song. (at present the seekbar does not change the position within the song. Heres my code
public class MusicPlayerA extends Activity {
private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2500, backwardTime = 2500;
private Handler durationHandler = new Handler();
private SeekBar seekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout of the Activity
setContentView(R.layout.musicplayerview);
//initialize views
initializeViews();
}
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.pause();
if (isFinishing()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
public void initializeViews(){
songName = (TextView) findViewById(R.id.songName);
mediaPlayer = MediaPlayer.create(this, R.raw.druidsad);
finalTime = mediaPlayer.getDuration();
duration = (TextView) findViewById(R.id.songDuration);
seekbar = (SeekBar) findViewById(R.id.seekBar);
songName.setText("Druids Ad");
seekbar.setMax((int) finalTime);
seekbar.setClickable(true);
}
// play mp3 song
public void play(View view) {
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
seekbar.setProgress((int) timeElapsed);
//set time remaining
double timeRemaining = finalTime - timeElapsed;
duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public void pause(View view) {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public void forward(View view) {
//check if we can go forward at forwardTime seconds before song endes
if ((timeElapsed + forwardTime) <= finalTime) {
timeElapsed = timeElapsed + forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// handler for back button used on music player screen
public void BackButton2 (View view) {
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
mMediaPlayer.start();
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(200);
Intent mus = new Intent (this, Music.class);
startActivity(mus);
}
// handler for home button used on all screens
public void BackButton (View view) {
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
mMediaPlayer.start();
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(200);
Intent mn = new Intent (this, Music.class);
startActivity(mn);
}
}
Its easy. Follow these steps :-
Add a seek bar change Listener.
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int seeked_progess;
#Override
public void onProgressChanged(final SeekBar seekBar, int progress, boolean fromUser) {
seeked_progess = progress;
seeked_progess = seeked_progess * 1000;
if (fromUser) {
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Now in if(fromUser), U need to add the implementation.
if (fromUser) {
Runnable mRunnable = new Runnable() {
#Override
public void run() {
int min, sec;
if (mediaPlayer != null /*Checking if the
music player is null or not otherwise it
may throw an exception*/) {
int mCurrentPosition = seekBar.getProgress();
min = mCurrentPosition / 60;
sec = mCurrentPosition % 60;
Log.e("Music Player Activity", "Minutes : "+min +" Seconds : " + sec);
/*currentime_mm.setText("" + min);
currentime_ss.setText("" + sec);*/
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();}
At last add this in onStopTrackingTouch()
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seeked_progess);
}
});
Note :-
mHandler in a global variable.
Initialize it as follows.
Handler mHandler = new Handler();
Secondly currentime_mm and currentime_ss are text views which display the current seek time of the seek bar.
and most Important,
dont forgot to add these when a song starts
seekBar.setProgress(0);// To set initial progress, i.e zero in starting of the song
seekBar.setMax(mediaDuration);// To set the max progress, i.e duration of the song
Put this code inside onCreate() method
seekbar.setMax(mediaPlayer.getDuration());
seekbar.setProgress(mediaPlayer.getCurrentPosition());
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run()
{
seekbar.setProgress(mediaPlayer.getCurrentPosition());
}
},0,1000);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b)
{
mediaPlayer.seekTo(i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
What Punam did is good but add a condition in your "onProgressChanged" function like this:
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b)
{
if(b)
mediaPlayer.seekTo(i);
}
I'm trying to implement a series of music players in Android. When I press the back button I want the music to stop when the application returns to the the previous screen. I tried lots of solutions and searched online but the app is crashing if I put in lines such as 'stop' and 'release'. Maybe I'm not doing them correctly? Thanks for any help forthcoming... Here is my code...
public class MusicPlayerA extends Activity {
private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2500, backwardTime = 2500;
private Handler durationHandler = new Handler();
private SeekBar seekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout of the Activity
setContentView(R.layout.musicplayerview);
//initialize views
initializeViews();
}
public void initializeViews(){
songName = (TextView) findViewById(R.id.songName);
mediaPlayer = MediaPlayer.create(this, R.raw.druidsad);
finalTime = mediaPlayer.getDuration();
duration = (TextView) findViewById(R.id.songDuration);
seekbar = (SeekBar) findViewById(R.id.seekBar);
songName.setText("Druids Ad");
seekbar.setMax((int) finalTime);
seekbar.setClickable(true);
}
// play mp3 song
public void play(View view) {
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
seekbar.setProgress((int) timeElapsed);
//set time remaining
double timeRemaining = finalTime - timeElapsed;
duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public void pause(View view) {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public void forward(View view) {
//check if we can go forward at forwardTime seconds before song endes
if ((timeElapsed + forwardTime) <= finalTime) {
timeElapsed = timeElapsed + forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
public void stopMusic(View view) {
mediaPlayer.stop();
mediaPlayer.release();
}
// handler for back button used on all screens
public void BackButton2 (View view) {
//mediaPlayer.pause();
//mediaPlayer.release();
//mediaPlayer.stop();
// mediaPlayer.release();
stopMusic(view);
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
mMediaPlayer.start();
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(200);
Intent mus = new Intent (this, Music.class);
startActivity(mus);
}
// handler for back button used on all screens
public void BackButton (View view) {
// mediaPlayer.pause();
//mediaPlayer.release();
// mediaPlayer.stop();
// mediaPlayer.release();
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
mMediaPlayer.start();
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(200);
Intent mn = new Intent (this, Music.class);
startActivity(mn);
}
}
When you hit the back button, the Android system should call on Activity.onPause(). I don't see any implementation for onPause(), unless your backbutton handler is calling it. I would try something like this:
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.pause();
if (isFinishing()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}