hi could some one show me how to add a progress bar to this method :
public boolean sendFile(String path,String ip, int port) {
// TODO Auto-generated method stub
try {
String[] str = ip.split("\开发者_StackOverflow\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
Log.i("SO sendFILE","");
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File(path);
String filename=path.substring(path.lastIndexOf("/")+1);
System.out.println("filename:"+filename);
fin.filename = "~"+filename;
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream(f);
Log.i("SocketOP", "sendFILE-2");
byte [] buffer = new byte [(int)f.length()];
System.out.println("SO sendFile f.length();" + f.length());
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, buffer.length);
System.out.println("SO sendFile" + bytesRead +filename);
}
out.flush();
out.close();
fileIn.close();
Log.i("SocketOP", "sendFILE-3");
} catch (IOException e) {
return false;
//e.printStackTrace();
}
// Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
return true;
}
thanks in advance.
ProgressDialog pbarDialog = new ProgressDialog( mContext );
pbarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pbarDialog.setMessage("Loading...");
pbarDialog.setCancelable(false);
pbarDialog.setMax(100);
pbarDialog .setProgress(0);
pbarDialog.show();
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, buffer.length);
//get the previous value of progress bar
int old_value = pbarDialog .getProgress();
//calculate how much did you read from the file
int new_read =(int)( ((float) bytesRead/f.length()) )*100 ) ;
//add the new read to the old_value
int value = new_read+old_value;
pbarDialog.setProgress(value);
System.out.println("SO sendFile" + bytesRead +filename);
}
pbarDialog.dismiss();
You would need to run that function from the UI thread in order to show a progress bar, but then you wouldn't get to see any progress until the function finished. The right approach for what you are trying to do is an AsyncTask, check
http://developer.android.com/reference/android/os/AsyncTask.html
精彩评论