异步任务报告错误的 Android 执行进度



我正在使用异步任务将SMS消息上传到Firebase,但是asyn任务立即在ProgressUpdate方法上执行,它不会报告实际进度,因为有多少项目入到Firebase。我想在上传消息时显示真正的进度。Asyn 任务会立即完成,但消息仍在 Firebase 控制台中添加。我怎样才能获得真正的进步。

法典:

 private class UploadConversations extends AsyncTask<Void, Integer, Integer> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Displays the progress bar for the first time.
        mBuilder.setProgress(totalMsgs, 0, false);
        mNotifyManager.notify(id, mBuilder.build());
    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        // Update progress
        mBuilder.setProgress(totalMsgs, values[0], false);
        mNotifyManager.notify(id, mBuilder.build());
        super.onProgressUpdate(values);
    }
    @Override
    protected Integer doInBackground(Void... params) {
        //Looping for the messages
               while(i < totalMsgs)
               {
                //Upload
                myRef = FirebaseDatabase.getInstance().getReference();
                //Log.v(LOGTAG, "Uploading chat id: " + item.getId());
                String msgID = _id + "";
                myRef.child("Chats").child(userID).child(thread_id).child(msgID).child("_id").setValue(_id);
                myRef.child("Chats").child(userID).child(thread_id).child(msgID).child("type").setValue(type);
                myRef.child("Chats").child(userID).child(thread_id).child(msgID).child("message").setValue(body); //body
                myRef.child("Chats").child(userID).child(thread_id).child(msgID).child("time").setValue(dateFormat.format(timestamp));
                myRef.child("Chats").child(userID).child(thread_id).child(msgID).child("time_stamp").setValue(timestamp); //Date

                i++;
                publishProgress(i);


            }
        }
        catch(Exception ex){
            Log.e(LOGTAG, ex.getMessage());
        }
        finally {  cur.close();}
        return null;
    }
    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        mBuilder.setContentTitle("Uploaded");
        mBuilder.setContentText("Backup completed");
        // Removes the progress bar
        mBuilder.setProgress(0, 0, false);
        mNotifyManager.notify(id, mBuilder.build());
        mNotifyManager.cancel(id);
        Toast.makeText(getApplicationContext(), "Backup completed", Toast.LENGTH_LONG).show();
    }

Firebase 数据库客户端已在后台线程中运行所有网络操作,而不会阻塞您的主线程。把它放在AsyncTask里不会带来任何额外的好处。

如果您想知道写入操作何时完成,DatabaseReference.setValue(...)返回一个 Task<Void> ,它允许您检测:

myRef.child("Chats").child(userID).child(thread_id).child(msgID).child("_id").setValue(_id).addOnSuccessListener(new OnSuccessListener() {
    @Override
    public void onSuccess() {
        // the write completed
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Uh-oh, an error occurred!
    }
});

在这种情况下,您可能希望将所有写入合并到一个setValue(...)调用中,以便可以检测它们何时全部完成:

Map<String, Object> values = new HashMap<String, Object>();
values.put("_id", _id);
values.put("type", type);
values.put("message", body);
values.put("time", dateFormat.format(timestamp));
values.put("time_stamp", timestamp);
myRef.child("Chats").child(userID).child(thread_id).child(msgID).setValue(values).addOnSuccessListener(new OnSuccessListener() {
    @Override
    public void onSuccess() {
        // the write completed
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Uh-oh, an error occurred!
    }
});

如果你想了解更多关于Task以及你可以用它们做什么,我强烈建议你阅读道格史蒂文森的成为任务大师博客系列。

最新更新