终止一个异步任务活性丢失后 [英] Terminating an Async Task after activity is lost

查看:137
本文介绍了终止一个异步任务活性丢失后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的过程和问题:

Here is my process and problem:


  1. 在此应用中,你点击一个菜单按钮

  1. In this application you click a Menu button

从该菜单preSS切换按钮,启动一个异步任务(使一个音每30秒的声音)。这个任务是运行时不断拨动检查,并取消当它被选中。这项工作的罚款,只要你留在菜单窗口来启动和停止的过程。

From this Menu you press a toggle button, which starts an Async-Task (makes a tone sound every 30 seconds). This task is to run constantly when the toggle is checked, and cancel when it is unchecked. This work's fine to start and stop the process as long as you remain in the Menu window.

检查转换框!

如果窗口被撕下和菜单再次打开,我保存状态的切换被选中并且进程仍在运行。不过我觉得我失去了进入异步任务的实例。这可能是为什么取消选中切换然后将程序崩溃?结果
myTask.cancle(真);可能就像丢了参考和我非同步,现在的任务是在虚空中流淌出来,我再也不能打电话或控制它!

If the window is peeled back and Menu is opened again, my save state for the toggle is Checked and the process is still running. However I THINK I lost access to that instance of the Async Task. Which might be why unchecking the toggle will then crash the program?
myTask.cancle(true); may be like a lost reference and my Asynch-Task is now flowing out in the void where I can no longer call to or control it!

我能做些什么来获取异步任务,在这种情况下取​​消?

What can I do to grab the Async task and cancel it in this situation?

TL,DR;
 如果我产卵异步任务从一个活动(mTask =新...),但随后离开这个活动,我怎么能仍然能够访问mTask?

TL,DR; If I spawn an async task from one activity (mTask = new ...), but then leave that activity, how can I still access mTask?

推荐答案

我觉得你不应该使用的AsyncTask API,它可用于运行一个耗时的任务后台线程,并提供了钩子,当它完成,或有中间结果来更新UI。

I think you should not use the AsyncTask API, which is intended for running a time consuming task in a background thread and provides hooks to update the UI when it finishes or has intermediate results.

您可以简单地使用的Runnable 和Singleton模式在整个活动构造和析构找到实例。喜欢的东西(不再赘述单样板)

You can simply use a Runnable and the singleton pattern to locate the instance across activities constructions and destructions. Something like (singleton boilerplate omitted for brevity)

public class Player implements Runnable {

  public static void start() {}

  @Override
  public void run() {
    while (alive) {
      playSound();
      sleep();
    }
  }

  public static void stop() {}

  public static boolean isAlive() {}

}

然后,当你初始化你的部件:

Then, when you initialize your widgets:

checkbox.setChecked(Player.isAlive());
checkbox.setOnCheckedStateChangeListener(new OnCheckedChangeListener(){
  @Override
  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (isChecked)
      Player.start();
    else
      Player.stop();
  }
});

这样,你的后台线程是从哪个开始的任何活动完全独立的。

This way your background thread is completely independent from any Activity which started it.

这篇关于终止一个异步任务活性丢失后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆