在安卓版本高于5(Lollipop,即API级别21)的应用程序中,下载文件并保存到应用程序文件夹涉及以下几个基础概念:
原因:在安卓6.0(API级别23)及以上版本,需要动态请求存储权限。
解决方法:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
}
原因:可能没有正确获取应用程序的私有文件夹路径。
解决方法:
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
if (directory != null) {
String path = directory.getAbsolutePath();
}
原因:可能是网络问题或下载管理器配置错误。
解决方法:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = manager.enqueue(request);
以下是一个完整的示例代码,展示了如何在安卓应用中下载文件并保存到应用程序文件夹:
import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
public class DownloadActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 123;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
} else {
startDownload();
}
}
private void startDownload() {
String url = "https://example.com/file.zip";
String fileName = "file.zip";
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
if (directory != null) {
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
long downloadId = manager.enqueue(request);
new Handler(Looper.getMainLooper()).postDelayed(() -> {
Toast.makeText(this, "Download completed", Toast.LENGTH_SHORT).show();
}, 5000); // Simulate download completion
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startDownload();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
}
通过以上步骤和示例代码,您可以在安卓版本高于5的应用程序中成功下载文件并保存到应用程序文件夹中。
领取专属 10元无门槛券
手把手带您无忧上云