Issue
I'm trying to cancle my AsyncTask
when I click Back Button
by using this code :
@Override
public void onBackPressed() {
super.onBackPressed();
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
if(playerTask!=null && !playerTask.isCancelled()) playerTask.cancel(true);
this.finish();
}
But doesn't work playerTask still works :
PlayerTask playerTask = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_for_ringtone);
mediaPlayer = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(url);
/***/
@SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar pb = findViewById(R.id.progress);
@Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
mediaPlayer.setAudioAttributes(attribs);
} else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
}
@Override
protected Boolean doInBackground(String... strings) {
if(!isCancelled()) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
}
else
{
playerTask.cancel(true);
}
return prepared;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
music.setEnabled(true);
music.setVisibility(View.VISIBLE);
music.setChecked(true);
}
}
Solution
Try this
@Override
public void onBackPressed() {
// if playerTask == null mediaPlayer is never start, no need to handle
if(playerTask != null && playerTask.getStatus() == AsyncTask.Status.FINISHED) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
} else if (playerTask != null && playerTask.getStatus() != AsyncTask.Status.FINISHED) {
// It mean your task is running, should stop your mediaPlayer inside your task
playerTask.cancel(true);
}
super.onBackPressed();
}
And in your PlayerTask override onCancelled
method
@Override
protected void onCancelled(Boolean aBoolean) {
if(isCancelled() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
Hope it help
Answered By - Truong Giang Dam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.