1

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);
        }
    }
ali
  • 189
  • 3
  • 14
  • I've dealt with these matters too and find myself a solution by using a service instead of asynctask. – statosdotcom Feb 06 '18 at 20:57
  • @statosdotcom thanks so much for your comment please can you give me some tutorial or docs about streaming radio using `service` – ali Feb 06 '18 at 21:04
  • AsyncTask is built for short tasks that require regular UI updates. You should look for other threading solution like a HandlerThread or an IntentService. – Harikumar Alangode Feb 07 '18 at 05:28

3 Answers3

1

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

dazed'n'confused
  • 231
  • 3
  • 13
0

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.

dgngulcan
  • 3,101
  • 1
  • 24
  • 26
0

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

tyczj
  • 71,600
  • 54
  • 194
  • 296
  • thanks so much for your comment but still doesn't work please see my new update post – ali Feb 06 '18 at 21:13
  • You dont need an asynctask to play music so you are doing unnecessary work by adding an asynctask. Trying to stop it isnt going to do anything for you. you should use `prepareAsync()` then you remove the need for it – tyczj Feb 06 '18 at 21:19
  • Right from the doc's `For streams, you should call prepareAsync(), which returns immediately, rather than blocking until enough data has been buffered.` https://developer.android.com/reference/android/media/MediaPlayer.html#prepareAsync() – tyczj Feb 06 '18 at 21:23
  • actually i'm using `asynctask` just for showing a `progressbar` while music doesn't play yet. so i show `progressbar` in `onPreExecute` and i hide it in `onPostExecute` please if i can use something else please tell me – ali Feb 06 '18 at 21:28