I use music in the background of my activity. But when I try to cancel it, it does not work. Music just works continuously until it ends. Below is the code:
public class xx extends Activity { BackgroundSound mBackgroundSound = new BackgroundSound(); @Override protected void onCreate(Bundle savedInstanceState) { .... } @Override protected void onResume() { super.onResume(); mBackgroundSound.execute(); } @Override protected void onPause() { super.onPause(); mBackgroundSound.cancel(true); }
and to select the options menu:
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mBackgroundSound.cancel(true); NavUtils.navigateUpFromSameTask(this); return true; case R.id.menu_Add: { mBackgroundSound.cancel(true); Intent intent = new Intent(xx.this,yy.class); intent.putExtra("flag", "add"); intent.putExtra("AddObj", "mm"); startActivity(intent); break; } case R.id.menu_list_quote: { mBackgroundSound.cancel(true); Intent intent = new Intent(xx.this,zz.class); intent.putExtra("Obj", "nn"); startActivity(intent); break; } }
and asynTask:
public class BackgroundSound extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { try { while( !isCancelled()) {
Also tried using for loop:
for(int i=0;i<100 && !isCancelled();i++)
and tried this inside the try asyncTask block:
if(isCancelled()) player.stop();
How can I solve it?
source share