Android ListView在长时间运行后不会更新

时间:2011-07-28 01:59:57

标签: android multithreading listview

我有一个相当复杂的问题。我已经阅读了一些与我的问题类似的帖子,但情况略有不同。

我有一个列表视图的活动。 Activity创建一个具有长时间运行过程的线程。在该过程结束后,它会调用处理程序来更新列表视图并播放声音。如果我在同一个Activity中,它工作正常,但是当进程运行时我点击HOME按钮,然后按快捷键或应用程序图标启动Activity,然后当进程结束时,我听到声音但是列表视图未更新。任何想法为什么会这样?有些人和我也因为方向改变而遇到同样的问题。

// thread created to send the reply.
   Thread replyThread = new Thread() {
public void run() {
    **Http POST here to upload an image which takes a while.    
//Once done, send a msg to handler to play a sound and update listview  
Message msg = replyHandler.sendEmptyMessage(0);         
}
   }

处理程序:

final Handler replyHandler = new Handler() {
    public void handleMessage(Message msg) {
    fillData();
    **Code to play sound.
    }
}

fillData()方法

// refresh the listview.
private void fillData() {
    // Get all of the rows from the database and create the item list

            **I actually have an activity before this one but to simplify the problem I said I have 1 Activity. Bundle is from previous Activity.

            String conversationId = "";

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        conversationId = extras
                .getString(TestDbAdapter.KEY_CONVERSATION_ID);          
    }

    if (mDbHelper != null) {        

        Cursor notesCursor = mDbHelper
                .fetchAllMessagesByConversationId(conversationId);
        startManagingCursor(notesCursor);

        String[] from = new String[] { TestDbAdapter.KEY_BODY,
                TestDbAdapter.KEY_TIMESTAMP };

        int[] to = new int[] { R.id.text1, R.id.text2 };

        // Now create a simple cursor adapter and set it to display
        MessagesCursorAdapter notes = new MessagesCursorAdapter(this,
                R.layout.messages_row, notesCursor, from, to, mDbHelper);
        setListAdapter(notes);

    }

}

我知道有些人会说“使用notifyDataSetChanged”,完成了。上面的代码与notifyDataSetChanged的工作方式相同,但可能不是非常优雅,但在我的情况下它可以工作,但它对我使用notifyDataSetChanged的问题没有帮助。

1 个答案:

答案 0 :(得分:0)

按下主页按钮并重新启动活动后,将创建“新”活动。

来自长时间运行流程的回调将被发送到旧活动,而不是新活动。

方向更改也会发生类似情况,每次方向更改都会创建一个新活动(不会收到回调)。

我知道有几种方法可以解决这个问题:

  • 存储状态&本地存储中长时间运行的进程(db,xml,contentprovider等)和查询状态&活动开始时的结果。 Google IO REST talk讨论了问题以及解决问题所能实现的模式。 (注意:完全实现此模式的工作量相当大)
  • 通过Application类路由回调并在应用程序启动时注册您的活动,以便它知道将回调发送到哪一个。 Droid-fu包含一些可以帮助实现此功能的实用程序
相关问题