我正在使用Thread下载文件表单服务器。我已按照下面提到的代码下载文件。
下载线程::
public class DownloaderThread extends Thread
{
// constants
private static final int DOWNLOAD_BUFFER_SIZE = 4096;
// instance variables
//private SettingsListFragment parentActivity;
private String downloadUrl;
/**
* Instantiates a new DownloaderThread object.
* @param inUrl String representing the URL of the file to be downloaded.
*/
public DownloaderThread(String inUrl)
{
downloadUrl = "";
if(inUrl != null)
{
downloadUrl = inUrl;
}
//parentActivity = inParentActivity;
}
/**
* Connects to the URL of the file, begins the download, and notifies the
* AndroidFileDownloader activity of changes in state. Writes the file to
* the root of the SD card.
*/
@Override
public void run()
{
URL url;
URLConnection conn;
int fileSize, lastSlash;
String fileName;
BufferedInputStream inStream;
BufferedOutputStream outStream;
File outFile;
FileOutputStream fileStream;
Message msg;
// we're going to connect now
msg = Message.obtain(activityHandler,MESSAGE_CONNECTING_STARTED,0, 0, downloadUrl);
activityHandler.sendMessage(msg);
try
{
url = new URL(downloadUrl);
conn = url.openConnection();
conn.setUseCaches(false);
fileSize = conn.getContentLength();
// get the filename
lastSlash = url.toString().lastIndexOf('/');
fileName = "file.bin";
if(lastSlash >=0)
{
fileName = url.toString().substring(lastSlash + 1);
}
if(fileName.equals(""))
{
fileName = "file.bin";
}
// notify download start
int fileSizeInKB = fileSize / 1024;
if(Utils.getAvailableExternalMemorySize() > fileSizeInKB)
{
msg = Message.obtain(activityHandler,MESSAGE_DOWNLOAD_STARTED,fileSizeInKB, 0, fileName);
activityHandler.sendMessage(msg);
// start download
inStream = new BufferedInputStream(conn.getInputStream());
outFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
System.out.println("#### Download File Location==>"+outFile);
fileStream = new FileOutputStream(outFile);
outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0, totalRead = 0;
while(!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0)
{
outStream.write(data, 0, bytesRead);
long total = 0;
// update progress bar
totalRead += bytesRead;
int totalReadInKB = totalRead / 1024;
int percentage=(int)((totalRead*100)/fileSize);
//msg = Message.obtain(activityHandler,MESSAGE_UPDATE_PROGRESS_BAR,totalReadInKB, 0);
msg = Message.obtain(activityHandler,MESSAGE_UPDATE_PROGRESS_BAR,totalReadInKB, percentage);
activityHandler.sendMessage(msg);
}
outStream.close();
fileStream.close();
inStream.close();
if(isInterrupted())
{
// the download was canceled, so let's delete the partially downloaded file
outFile.delete();
}
else
{
// notify completion
msg = new Message();
msg.what=MESSAGE_DOWNLOAD_COMPLETE;
msg.obj=fileName;
msg.obj=outFile;
//msg = Message.obtain(parentActivity.activityHandler,
//AndroidFileDownloader.MESSAGE_DOWNLOAD_COMPLETE);
activityHandler.sendMessage(msg);
}
}
else
{
String errMsg = getActivity().getString(R.string.msg_error_insufficient_storage);
msg = Message.obtain(activityHandler,MESSAGE_ENCOUNTERED_ERROR,0, 0, errMsg);
activityHandler.sendMessage(msg);
}
}
catch(MalformedURLException e)
{
String errMsg = getActivity().getString(R.string.msg_error_message_bad_url);
msg = Message.obtain(activityHandler,MESSAGE_ENCOUNTERED_ERROR,0, 0, errMsg);
activityHandler.sendMessage(msg);
}
catch(FileNotFoundException e)
{
String errMsg = getActivity().getString(R.string.msg_error_message_file_not_found);
msg = Message.obtain(activityHandler,MESSAGE_ENCOUNTERED_ERROR,0, 0, errMsg);
activityHandler.sendMessage(msg);
}
catch(Exception e)
{
String errMsg = getString(R.string.msg_error_message_general);
msg = Message.obtain(activityHandler,MESSAGE_ENCOUNTERED_ERROR,0, 0, errMsg);
activityHandler.sendMessage(msg);
}
}
}
这是我的活动处理程序
public Handler activityHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch(msg.what)
{
/*
* Handling MESSAGE_UPDATE_PROGRESS_BAR:
* 1. Get the current progress, as indicated in the arg1 field
* of the Message.
* 2. Update the progress bar.
*/
case MESSAGE_UPDATE_PROGRESS_BAR:
if(downloading.progress != null)
{
int currentProgress = msg.arg1;
int percentage=msg.arg2;
System.out.println("current Progrss=>"+currentProgress);
System.out.println(" % =>"+percentage);
if(downloading.tvPercentage!=null)
{
downloading.tvPercentage.setText(String.valueOf(percentage) + " %");
}
downloading.progress.setProgress(currentProgress);
}
break;
/*
* Handling MESSAGE_CONNECTING_STARTED:
* 1. Get the URL of the file being downloaded. This is stored
* in the obj field of the Message.
* 2. Create an indeterminate progress bar.
* 3. Set the message that should be sent if user cancels.
* 4. Show the progress bar.
*/
case MESSAGE_CONNECTING_STARTED:
if(msg.obj != null && msg.obj instanceof String)
{
System.out.println("MESSAGE_CONNECTING_STARTED ==>"+msg.toString());
String url = (String) msg.obj;
// truncate the url
if(url.length() > 16)
{
String tUrl = url.substring(0, 15);
tUrl += "...";
url = tUrl;
}
String pdTitle = getActivity().getString(R.string.msg_progress_dialog_title_connecting);
String pdMsg = getActivity().getString(R.string.msg_progress_dialog_message_prefix_connecting);
pdMsg += " " + url;
dismissCurrentProgressDialog();
if(pd.isShowing())
{
pd.dismiss();
}
progressDialog = new ProgressDialog(context);
progressDialog.setTitle(pdTitle);
progressDialog.setMessage(pdMsg);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
// set the message to be sent when this dialog is canceled
Message newMsg = Message.obtain(this, MESSAGE_DOWNLOAD_CANCELED);
progressDialog.setCancelMessage(newMsg);
progressDialog.show();
}
break;
/*
* Handling MESSAGE_DOWNLOAD_STARTED:
* 1. Create a progress bar with specified max value and current
* value 0; assign it to progressDialog. The arg1 field will
* contain the max value.
* 2. Set the title and text for the progress bar. The obj
* field of the Message will contain a String that
* represents the name of the file being downloaded.
* 3. Set the message that should be sent if dialog is canceled.
* 4. Make the progress bar visible.
*/
case MESSAGE_DOWNLOAD_STARTED:
// obj will contain a String representing the file name
if(msg.obj != null && msg.obj instanceof String)
{
System.out.println("Download Started ==>"+msg.toString());
int maxValue = msg.arg1;
String fileName = (String) msg.obj;
String pdTitle = getActivity().getString(R.string.msg_progress_dialog_title_downloading);
String pdMsg = getActivity().getString(R.string.msg_progress_dialog_message_prefix_downloading);
pdMsg += " " + fileName;
dismissCurrentProgressDialog();
downloading=new custom_progressDialog(getActivity());
downloading.setCanceledOnTouchOutside(false);
downloading.progress.setProgress(0);
downloading.progress.setMax(maxValue);
downloading.show();
// set the message to be sent when this dialog is canceled
Message newMsg = Message.obtain(this, MESSAGE_DOWNLOAD_CANCELED);
/*progressDialog.setCancelMessage(newMsg);
progressDialog.setCancelable(true);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();*/
}
break;
/*
* Handling MESSAGE_DOWNLOAD_COMPLETE:
* 1. Remove the progress bar from the screen.
* 2. Display Toast that says download is complete.
*/
case MESSAGE_DOWNLOAD_COMPLETE:
final String downloadedFilePath=msg.obj.toString();
dismissCurrentProgressDialog();
if(pd!=null && pd.isShowing())
{
pd.dismiss();
}
download_successfulDialog successfulDialg=new download_successfulDialog(getActivity(),downloadedFilePath);
successfulDialg.setCanceledOnTouchOutside(false);
successfulDialg.show();
//displayMessage(getString(R.string.user_message_download_complete));
//displayMessage("File has been successfully download at "+downloadedFilePath);
break;
/*
* Handling MESSAGE_DOWNLOAD_CANCELLED:
* 1. Interrupt the downloader thread.
* 2. Remove the progress bar from the screen.
* 3. Display Toast that says download is complete.
*/
case MESSAGE_DOWNLOAD_CANCELED:
if(downloaderThread != null)
{
downloaderThread.interrupt();
}
dismissCurrentProgressDialog();
if(pd!=null && pd.isShowing())
{
pd.dismiss();
}
//displayMessage()
displayMessage(getString(R.string.msg_user_message_download_canceled));
break;
/*
* Handling MESSAGE_ENCOUNTERED_ERROR:
* 1. Check the obj field of the message for the actual error
* message that will be displayed to the user.
* 2. Remove any progress bars from the screen.
* 3. Display a Toast with the error message.
*/
case MESSAGE_ENCOUNTERED_ERROR:
// obj will contain a string representing the error message
if(msg.obj != null && msg.obj instanceof String)
{
String errorMessage = (String) msg.obj;
dismissCurrentProgressDialog();
if(pd!=null && pd.isShowing())
{
pd.dismiss();
}
displayMessage(errorMessage);
}
break;
default:
// nothing to do here
break;
}
}
};
现在,在下载文件时,我得到的百分比值为负数。
请注意,在测试时,我发现摩托罗拉G设备和Micromax设备中存在奇怪的问题,显示三星设备中没有发生的百分比负值。
任何想法???
非常感谢...