android progress bar
hi am trying to add a progress bar to my activity, no clue how 开发者_如何学Goto do that. here is the scenario : my activity MESSAGING calls IMSERVICE.SENDFILE(), i pass the context from MESSAGING as argument to IMSERVICE.SENDFILE(). IMSERVICE.SENDFILE() calls SOCKETOPERATOR.SENDFILE(). i pass the same context to that too. SOCKETOPERATOR.SENDFILE() has a method that sends file and that looks like this :
public boolean sendFile(Context c,String path,String ip, int port) {
// TODO Auto-generated method stub
try {
String[] str = ip.split("\\.");
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;
ProgressDialog pbarDialog = new ProgressDialog(c);
pbarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pbarDialog.setMessage("Loading...");
pbarDialog.setCancelable(false);
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) f.length() / bytesRead)*100);
//add the new read to the old_value
int value = new_read+old_value;
pbarDialog.setProgress(value);
Log.i("SocketOP", "sendFILE-3");
System.out.println("SO sendFile" + bytesRead +filename);
}
pbarDialog.dismiss();
out.flush();
out.close();
fileIn.close();
} catch (IOException e) {
return false;
//e.printStackTrace();
}
// Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
return true;
}
now as you can see i have a progressbar in it. i dont know how to make it show from my MESSAGING activity. also, im not sure if i have used the progressDilog correctly. could anyone help please?
You should do the processing in a background thread, while calling the progress dialog and other UI related stuff in the UI thread. Thats what AsyncTask was designed to do, read about it here: http://developer.android.com/reference/android/os/AsyncTask.html
精彩评论