应用关闭后停止AsyncTask

时间:2018-02-06 20:41:59

标签: android service android-asynctask android-mediaplayer

我正在尝试创建一个使用AsynTask在后​​台播放音乐的广播流应用,我的应用也使用WallpaperService设置了Gif动态壁纸功能。

我的问题

  1. 当我设置一些gif作为壁纸时,当我尝试关闭应用程序时 从最近的任务或左/右滑动我的应用程序仍然没有 播放音乐AsynTask仍在(doInBackground),我发现了一个问题 在AsynTask完成时,音乐开始播放 即使我的申请已经关闭,也会有背景。
  2. 我想要什么

    1. 当我设置一些gif作为壁纸时,当我关闭我的应用程序时,我想 停止AsynTask
    2. 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);
              }
          }
      

3 个答案:

答案 0 :(得分:1)

删除Asynctask。因为您使用asynctask只是为了显示进度条。您可以在 onCreate()中将进度条设置为VISIBLE,然后在 mediaPlayer.setOnPreparedListener()

中将其设置为GONE

答案 1 :(得分:0)

您可以在cancel(true) AsyncTask功能中拨打doInBackground()。为此,您可以在AsyncTask中保留一个布尔标记,并在doInBackgroundcancel(true)内检查它是否被取消。

答案 2 :(得分:0)

没有“停止”异步任务。你打电话取消你的任务,但是在你的doInBackground代码中,你应该检查你的任务是否被取消,如果是,那就突破。

请参阅此参考资料

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