嗨,我试图添加一个进度条到我的活动,没有线索如何做到这一点。这是一个场景:我的活动消息传递调用IMSERVICE.SENDFILE(),我将消息传递中的上下文作为参数传递给IMSERVICE.SENDFILE()。IMSERVICE.SENDFILE()调用SOCKETOPERATOR.SENDFILE()。我也将同样的上下文传递给这一点。SOCKETOPERATOR.SENDFILE()有一个发送文件的方法,看起来像这样:
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;
}现在你可以看到我有一个进度条在里面。我不知道如何从我的消息活动中显示它。另外,我不确定我是否正确地使用了progressDilog。有人能帮帮忙吗?
发布于 2011-09-12 06:22:23
您应该在后台线程中进行处理,同时在UI线程中调用进度对话框和其他与UI相关的内容。这就是AsyncTask设计的目的,请在这里阅读:http://developer.android.com/reference/android/os/AsyncTask.html
https://stackoverflow.com/questions/7381667
复制相似问题