Computer >> 컴퓨터 >  >> 프로그램 작성 >> Android

Android에서 실행 중인 AsyncTask를 취소하는 방법은 무엇입니까?

<시간/>

예제를 시작하기 전에 Android에서 AsyncTask가 무엇인지 알아야 합니다. AsyncTask는 백그라운드 스레드에서 작업/작업을 수행하고 메인 스레드에서 업데이트합니다. 백그라운드 스레드에서 백그라운드 작업을 수행하는 동안 사용자는 다음 코드를 사용하여 작업을 취소할 수 있습니다. -

AsynTaskExample mAsyncTask = new AsyncTaskExample();
mAsyncTask.cancel(true);

이 예제는 Android에서 실행 중인 AsyncTask를 취소하는 방법을 보여줍니다.

1단계 − Android Studio에서 새 프로젝트를 생성하고 파일 ⇒ 새 프로젝트로 이동하여 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.

2단계 − res/layout/activity_main.xml에 다음 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
   xmlns:tools = "https://schemas.android.com/tools"
   android:id = "@+id/rootview"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical"
   android:background = "#c1c1c1"
   android:gravity = "center_horizontal"
   tools:context = ".MainActivity">
   <Button
      android:id = "@+id/asyncTask"
      android:text = "Download"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content" />
   <ImageView
      android:id = "@+id/image"
      android:layout_width = "300dp"
      android:layout_height = "300dp" />
</LinearLayout>

위의 코드에서 버튼을 클릭하면 인터넷 소스에서 이미지를 다운로드하고 imageview에 추가합니다.

3단계 − src/MainActivity.java

에 다음 코드 추가
package com.example.andy.myapplication;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
   URL ImageUrl = null;
   InputStream is = null;
   Bitmap bmImg = null;
   ImageView imageView = null;
   AsyncTaskExample asyncTask = null;
   ProgressDialog p;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Button button = findViewById(R.id.asyncTask);
      imageView = findViewById(R.id.image);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            asyncTask = new AsyncTaskExample();
            asyncTask.execute("https://www.tutorialspoint.com/images/tp-logo-diamond.png");
         }
      });
   }
   private class AsyncTaskExample extends AsyncTask {
      @Override
      protected void onPreExecute() {
         super.onPreExecute();
         p = new ProgressDialog(MainActivity.this);
         p.setMessage("Please wait...It is downloading");
         p.setIndeterminate(true);
         p.setCancelable(true);
         p.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
               asyncTask.cancel(true);
               Toast.makeText(MainActivity.this,"AsyncTask is stopped",Toast.LENGTH_LONG).show();
            }
         });
         p.show();
      }
      @Override
      protected Bitmap doInBackground(String... strings) {
         try {
            try {
               Thread.sleep(10000);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
            ImageUrl = new URL(strings[0]);
            HttpURLConnection conn = (HttpURLConnection) ImageUrl .openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            bmImg = BitmapFactory.decodeStream(is, null, options);
         } catch (IOException e) {
            e.printStackTrace();
         }
         return bmImg;
      }
      @Override
      protected void onPostExecute(Bitmap bitmap) {
         super.onPostExecute(bitmap);
         if(imageView! = null) {
            p.hide();
            imageView.setImageBitmap(bitmap);
         } else {
            p.show();
         }
      }
   }
}

4단계 − manifest.xml에 다음 코드 추가

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
   package = "com.example.andy.myapplication">
   <uses-permission android:name = "android.permission.INTERNET"/>
   <application
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:roundIcon = "@mipmap/ic_launcher_round"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
      <activity android:name = ".MainActivity">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

위의 코드에서 우리는 인터넷 소스에서 이미지를 가져올 수 있는 권한을 인터넷에 부여했습니다.

응용 프로그램을 실행해 보겠습니다. 실제 Android 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 도구 모음에서 아이콘 실행을 클릭합니다. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 -

Android에서 실행 중인 AsyncTask를 취소하는 방법은 무엇입니까?

위의 버튼을 클릭하면 진행 표시줄이 시작되고 진행 표시줄이 아닌 아무 곳이나 클릭하면 다음과 같은 화면이 나옵니다.

Android에서 실행 중인 AsyncTask를 취소하는 방법은 무엇입니까?

위의 화면은 비동기 작업이 중지되고 이제 인터넷 소스에서 이미지가 다운로드되었음을 명확하게 보여줍니다.

Android에서 실행 중인 AsyncTask를 취소하는 방법은 무엇입니까?

비동기 작업을 중지하지 않으면 위와 같이 이미지가 다운로드됩니다.