ali
ali

Reputation: 199

Stop AsyncTask when app is closed

i'm trying to create a radio stream app that play music in background using AsynTask, also my app have a Set Gif As Live Wallpaper feature using WallpaperService.

MY PROBLEM

  1. When i set some gif as wallpaper and when i try to close the app from recent task or by swiping left/right and my app still doesn't play music AsynTask still in (doInBackground) ,I find a problem here when AsynTask finished ,music starts playing in the background even though my application has been closed.

WHAT I WANT

  1. When i set some gif as wallpaper and when i close my app i want to stop AsynTask .

MainActivity :

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        playerTask = new PlayerTask();
        playerTask.execute("URL_STREAM");

}

@Override
    protected void onDestroy() {
        super.onDestroy();
        MApplication.sBus.post(PlaybackEvent.CLOSE);
        try {
            MApplication.sBus.unregister(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

   @Subscribe
    public void handlePlaybackEvent(PlaybackEvent event) {
        switch (event) {
            case PAUSE:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    MusicButton.setChecked(true);
                }
                break;
            case PLAY:
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                    MusicButton.setChecked(false);
                }
                break;
            case CLOSE:
                MApplication.sBus.post(PlaybackEvent.PAUSE);
                NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                assert n != null;
                n.cancelAll();
                playerTask.cancel(true);

    }

 @SuppressLint("StaticFieldLeak")
    public class PlayerTask extends AsyncTask<String, Void, Boolean> {
        ProgressBar loadingRL = findViewById(R.id.progressBar);

        @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);
            }
            loadingRL.setVisibility(View.VISIBLE);
            beforradio.start();
        }

        @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();

                }
            });
        }
            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            MusicButton.setVisibility(View.VISIBLE);
            MusicButton.setChecked(true);
            loadingRL.setVisibility(View.GONE);
             /*get details : */
            Uri uri = Uri.parse(JsonData.NightWavePlazaRadioStream);
            OnNewMetadataListener ilistener = new OnNewMetadataListener() {
                @Override
                public void onNewHeaders(String stringUri, List<String> name, List<String> desc, List<String> br, List<String> genre, List<String> info) {
                }

                @Override
                public void onNewStreamTitle(String stringUri, String streamTitle) {
                    Animation a = AnimationUtils.loadAnimation(MainActivity.this, R.anim.textanim);
                    a.reset();
                    songinfo.setText("Song : " + streamTitle);
                    createNotification(getApplicationContext(), streamTitle, "notificationchannel", notificationManager);

                }
            };
            AudiostreamMetadataManager.getInstance()
                    .setUri(uri)
                    .setOnNewMetadataListener(ilistener)
                    .setUserAgent(UserAgent.WINDOWS_MEDIA_PLAYER)
                    .start();
            Rlsong.setVisibility(View.VISIBLE);
        }
    }

Upvotes: 1

Views: 1066

Answers (3)

Remove Asynctask. Since you are using asynctask just to show the progress bar. You can set your progressbar VISIBLE in onCreate() then set it GONE inside mediaPlayer.setOnPreparedListener()

Upvotes: 1

dgngulcan
dgngulcan

Reputation: 3149

You can call cancel(true) inside your AsyncTasks doInBackground() function. To do that, you can keep a boolean flag inside your AsyncTask and check if it is canceled or not inside doInBackground and cancel(true) if it is cancelled.

Upvotes: 0

tyczj
tyczj

Reputation: 73753

There is no "stopping" an async task. you call cancel on your task but in your doInBackground code you should be checking if your task was cancelled or not then break out if it was.

See this for reference

https://stackoverflow.com/a/6053943/599346

Upvotes: 0

Related Questions