我一直在尝试使用AsyncTask
更新我的通知进度条,但不知何故,它无效。进度始终保持为零,我的应用程序冻结。我想,这是因为频繁的数据更新到进度条。所以,我只是以5的倍数更新进度。我已经尝试了所有方法,但它们似乎都没有工作。这是我的AsyncTask实现:
private class ConnectToServerTask extends AsyncTask<Void, Integer, Void> {
NotificationManager mNotifyMgr;
NotificationCompat.Builder mBuilder;
int mNotificationId;
@Override
protected void onPreExecute() {
super.onPreExecute();
final TextView recLog=(TextView)findViewById(R.id.recLog);
recLog.append("On pre-execute");
mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mBuilder= new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("X-Files")
.setContentText("Copy in progress")
.setAutoCancel(true);
mNotificationId = 001;
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
@Override
protected Void doInBackground(Void... params) {
final EditText ipText=(EditText)findViewById(R.id.ipText);
try {
serverIP=InetAddress.getByName(ipText.getText().toString());
socket = new Socket(serverIP, 4444);
if (socket != null) {
InputStream min=socket.getInputStream();
int filecount=min.read(); //read file count from server
for (int j = 0; j < filecount; j++){
try {
InputStream in = socket.getInputStream();
int buffersize = socket.getReceiveBufferSize();
DataInputStream clientData = new DataInputStream(in);
String recFileName = clientData.readUTF(); // read file name
FileOutputStream output = new FileOutputStream(
downloadFolderPath +"/" + recFileName);
byte[] buffer = new byte[buffersize];
long filesize = clientData.readLong(); // read file size
double nosofpackets=Math.ceil(((int) filesize)/buffer.length);
long z = filesize;
int n = 0;
int k=1;
while ((z > 0)
&& (n = clientData.read(buffer, 0,
(int) Math.min(buffer.length, z))) != -1) {
output.write(buffer, 0, n);
int progressint=(int)(k*100/nosofpackets);
publishProgress(progressint);
output.flush();
z -= n;
}
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
@Override
protected void onProgressUpdate(Integer...values) {
super.onProgressUpdate(values);
if ((values[0])%5==0){
mBuilder.setProgress(100, values[0], false);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
}
任何帮助都将受到高度赞赏!提前谢谢!