ความรู้พื้นฐาน: AsyncTask ใน Android
AsyncTask ทำงานใน Background Thread และอัปเดต UI บน Main Thread ระหว่างทำงานใน Background ผู้ใช้สามารถยกเลิกได้ด้วยโค้ด:
AsyncTaskExample mAsyncTask = new AsyncTaskExample(); mAsyncTask.cancel(true);
ตัวอย่าง: การยกเลิก AsyncTask ที่กำลังทำงาน
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็น
ขั้นตอนที่ 2: จัดการ Layout (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="ดาวน์โหลด"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/image"
android:layout_width="300dp"
android:layout_height="300dp" />
</LinearLayout>
มี Button เริ่มดาวน์โหลดรูปภาพจากอินเทอร์เน็ต และ ImageView แสดงผล
ขั้นตอนที่ 3: เขียนโค้ด MainActivity (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<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(MainActivity.this);
p.setMessage("กรุณารอสักครู่...กำลังดาวน์โหลด");
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 ถูกหยุดแล้ว", 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 (AndroidManifest.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>
ต้องเพิ่ม Permission INTERNET เพื่อดาวน์โหลดรูปภาพจากอินเทอร์เน็ต
การทดสอบแอปพลิเคชัน
เชื่อมต่ออุปกรณ์ Android จริง ใน Android Studio คลิกไอคอน Run เลือกอุปกรณ์ แล้วตรวจสอบหน้าจอ

กดปุ่ม "ดาวน์โหลด" จะแสดง ProgressBar คลิกที่อื่นนอก ProgressBar จะยกเลิก:

แสดงข้อความ "AsyncTask ถูกหยุดแล้ว" และรูปภาพไม่ถูกดาวน์โหลด

หากไม่ยกเลิก จะดาวน์โหลดรูปภาพสำเร็จและแสดงใน ImageView