code

Android에서 asynctask 스레드를 중지하는 방법은 무엇입니까?

codestyles 2021. 1. 10. 17:17
반응형

Android에서 asynctask 스레드를 중지하는 방법은 무엇입니까?


AsyncTask다른 AsyncTask스레드 에서 스레드 를 중지하고 싶습니다 . new AsyncTask.cancel(true)백그라운드 프로세스를 중지 하려고했지만 멈추지 않았습니다.

아무도 이것에 대해 나를 도울 수 있습니까?


활동에서 asyncTask를 선언하십시오.

private YourAsyncTask mTask;

다음과 같이 인스턴스화하십시오.

mTask = new YourAsyncTask().execute();

다음과 같이 죽이거나 취소하십시오.

mTask.cancel(true);

일이 멈추지 않는 이유는 프로세스 (doInBackground ())가 완료 될 때까지 실행되기 때문입니다. 따라서 작업을 수행하기 전에 스레드가 취소되었는지 여부를 확인해야합니다.

if(!isCancelled()){
// Do your stuff
}

따라서 기본적으로 스레드가 취소되지 않은 경우 수행하고, 그렇지 않으면 건너 뜁니다. :) 작업 중, 특히 작업을 수행하기 전에이를 확인하는 데 유용 할 수 있습니다.

또한 약간 "정리"하는 것이 유용 할 수 있습니다.

onCancelled();

AsyncTask에 대한 문서 :

http://developer.android.com/reference/android/os/AsyncTask.html

도움이 되었기를 바랍니다!


당신은 또한에서 사용 할 수 있습니다 onPause또는 onDestroyActivity수명주기 :

//you may call the cancel() method but if it is not handled in doInBackground() method
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
    loginTask.cancel(true);

loginTask당신의 대상은 어디에 있습니까AsyncTask

감사합니다.


asynctask를 즉시 죽일 수는 없습니다. 중지하려면 먼저 취소해야합니다.

task.cancel(true);

asynctask의 doInBackground () 메서드 에서보다 이미 취소되었는지 확인합니다.

isCancelled()

그렇다면 수동으로 실행을 중지하십시오.


비슷한 문제가있었습니다. 기본적으로 사용자가 조각을 파괴 한 후 비동기 작업에서 NPE를 얻었습니다. Stack Overflow에서 문제를 조사한 후 다음 솔루션을 채택했습니다.

volatile boolean running;

public void onActivityCreated (Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    running=true;
    ...
    }


public void onDestroy() {
    super.onDestroy();

    running=false;
    ...
}

Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.


u can check onCancelled() once then :

protected Object doInBackground(Object... x) {

while (/* condition */) {
  if (isCancelled()) break;
}
return null;

}

ReferenceURL : https://stackoverflow.com/questions/7821284/how-to-stop-asynctask-thread-in-android

반응형