Android/Java,API级别12。
我正在尝试检查Downloads文件夹中是否存在.zip文件。如果不存在,则使用DownloadManager
从Internet下载。出于测试目的,我在DownloadManager的onReceive
方法之后立即运行checkIfFileExists
,前提是下载成功。我的问题是checkIfFileExists
每次都返回false
,即使我已经下载了这个文件,并且手动检查了它是否存在。相关代码如下。
DownloadManager dm;
long queueid;
String filename = "myfile.zip", url = "http://myurl/", uriString = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action))
{
DownloadManager.Query req_query = new DownloadManager.Query();
req_query.setFilterById(queueid);
Cursor c = dm.query(req_query);
if (c==null)
{
Toast.makeText(context, "Download not found!", Toast.LENGTH_SHORT).show();
}
else
{
if (c.moveToFirst())
{
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL==c.getInt(columnIndex))
{
uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Toast.makeText(context, "Download finished.", Toast.LENGTH_SHORT).show();
Toast.makeText(context, uriString, Toast.LENGTH_LONG).show();
checkIfFileExists();
}
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClickDownload(View v) // this method seems to be working with no issues.
{
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, filename);
queueid = dm.enqueue(request);
}
private boolean checkIfFileExists()
{
File file = new File(uriString);
if(file.exists())
{
Toast.makeText(this, "Exists", Toast.LENGTH_SHORT).show();
return true;
}
else
{
Toast.makeText(this, "Doesn't exist", Toast.LENGTH_SHORT).show();
return false;
}
}
我希望if(file.exists())
的计算结果为true
,因为该文件确实存在。
实际发生的是if(file.exists())
总是计算为false
。
有人知道我哪里做错了吗?
1条答案
按热度按时间juud5qan1#
像这样改变你的方法。: