既懂业务逻辑也懂工程实现
Android Studio
```kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val downloadButton = findViewById
val urlEditText = findViewById
downloadButton.setOnClickListener(View.OnClickListener {
val url = urlEditText.text.toString()
// Start a download task
DownloadTask(this).execute(url)
})
}
// AsyncTask to download the file
private class DownloadTask internal constructor(context: Context) : AsyncTask
private val context: Context = context
private var mProgressDialog: ProgressDialog? = null
override fun onPreExecute() {
super.onPreExecute()
// Create and show a progress dialog
mProgressDialog = ProgressDialog(context)
mProgressDialog?.setTitle("Downloading...")
mProgressDialog?.setMessage("Please wait...")
mProgressDialog?.setCancelable(false)
mProgressDialog?.show()
}
override fun doInBackground(vararg params: String): String {
val url = params[0]

// Download the file
val file = URL(url).openConnection().getInputStream()
val bytes = file.readBytes()
// Save the file to the device
val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
val fileName = "downloaded_file.jpg"
val fileOutputStream = FileOutputStream("$path/$fileName")
fileOutputStream.write(bytes)
fileOutputStream.close()
return "File downloaded successfully"
}
override fun onPostExecute(result: String) {
super.onPostExecute(result)
// Dismiss the progress dialog
mProgressDialog?.dismiss()
// Show a toast message
Toast.makeText(context, result, Toast.LENGTH_SHORT).show()
}
}
}
```
XML Layout
```xml
xmlns:app="http://schemas.android/apk/res-auto" xmlns:tools="http://schemas.android/tools" android:layout_width="match_parent" android:layout_height="match_parent"> android:id="@+id/url_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter URL" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
```