我看过很多关于android下载管理器的教程,每个教程都是相同的。但是问题是我在使用后在应用中使用了此代码,但是每当我单击此按钮时,我的应用就会崩溃。我的版本是android棉花糖,我的代码在这里。我也想问一下,我在互联网清单和外部存储清单中具有三个权限。我还想知道,“可以,可以将下载文件保存在我的应用程序文件夹中”
public class Dashboard extends AppCompatActivity {
Button btn;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View view){
String url = "http://www.myweb.com/abc.png";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
// only download via WIFI
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setTitle("Example");
request.setDescription("Downloading a very large zip");
// we just want to download silently
request.setVisibleInDownloadsUi(false);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
request.setDestinationInExternalFilesDir(context, null, "large.zip");
// enqueue this request
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadID = downloadManager.enqueue(request);
}
});
}
}
答案 0 :(得分:0)
我在您的代码中发现了两个错误。第一个是显示404的网址。另一个是您未提供下载目录。
请尝试以下代码片段-希望它能解决您的问题。
public class Dashboard extends AppCompatActivity {
Button btn;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View view){
String url = "http://www.myweb.com/abc.png"; // Please use a valid url. This url is says 404 not found.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
// only download via WIFI
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setTitle("Example");
request.setDescription("Downloading a very large zip");
// we just want to download silently
request.setVisibleInDownloadsUi(false);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
request.setDestinationInExternalFilesDir(context, Environment.getExternalStorageDirectory().getAbsolutePath(), "2.gif");
// enqueue this request
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadID = downloadManager.enqueue(request);
}
});
}
}