2016-07-18 18 views
0

我想在android聊天線程中將所有消息標記爲已讀。我使用的是從AOSP項目中複製的以下代碼,但是我的應用進入了ANR,並且我一直在日誌中收到以下消息。將Android Sms對話標記爲已讀。 Sql查詢得到一次又一次的執行。(錯誤)

ContentValues sReadContentValues = new ContentValues(2); 
sReadContentValues.put("read", 1); 
sReadContentValues.put("seen", 1); 
private static final String UNREAD_SELECTION = "(read=0 OR seen=0)"; 
context.getContentResolver().update(threadUri, sReadContentValues, UNREAD_SELECTION, null); 

登錄消息中環

SQLiteConnectionPool: executeForChangedRowCount started 152577ms ago - running, sql="UPDATE sms SET read=?,seen=? WHERE (read=0 OR seen=0) AND thread_id=1464" 

我一直在努力修復這個問題,因爲我們的,但仍然沒有運氣反覆。

回答

1

這是一個古老的線程,但我發現它在尋找如何正確利用ContentValue類型,它回答我的問題,我會回答它...

環流式日誌消息: 你有隻發佈了你的代碼的一小部分,所以我最好的猜測是你每次選擇一條消息時都會執行這個更新 - 在你的代碼循環中。如果這個這種情況,因爲你試圖在一次執行中更新整個線程,所以把這段代碼放到它自己的方法中(假設它還沒有)並且只調用一次是合乎邏輯的,AFTER你收到了所有需要的信息,並且你退出了循環。

應用進入ANR 雖然你已經發布的日誌消息讀 「(讀= 0或看到= 0)的thread_id = 1464」,你的代碼只反映 「(讀= 0或看到= 0)」在你的Where子句中 - 這顯然會導致一些挫敗感,因爲你會試圖更新每條消息線程中的每條消息。

雖然嘗試更新所有現有線程的方法會使處理器非常耗時,如果您還在循環內執行此操作(如您的Log消息所暗示的那樣),那麼您很有道理收到一個ANR,即使你包括它只有一個單一的thread_id運行的要求...

解決方案: 隨時糾正我,但做一些合理的假設,我相信這是您的解決方案:

public void mainMethod() 
{ 
    String threadId = "1464"; 
    Cursor cursor = getSomeMessages(threadId); 
    if (cursor != null && cursor.moveToFirst()) { 
     do { 
      // ... Do something with the message 
     } while (cursor.moveToNext()); 
     cursor.close(); 
    } 

    updateMessagesToReadAndSeen(threadId); 
} 

private void updateMessagesToReadAndSeen(String threadId) { 
    if (threadId != null && !threadId.isEmpty()) { 
     ContentValues sReadContentValues = new ContentValues(2); 
     sReadContentValues.put("read", 1); 
     sReadContentValues.put("seen", 1); 
     String UNREAD_SELECTION = "(read=0 OR seen=0) AND thread_id=" + threadId; 
     context.getContentResolver().update(threadUri, sReadContentValues, UNREAD_SELECTION, null); 
    } 
} 

我想如果我不得不對「適用範圍更改」提出一些建議,那麼可以將其分解爲更靈活的方法。如...

private void UpdateContent(Uri uri, ContentValues values, String _where, String[] args) { 
    _context.getContentResolver().update(uri, values, _where, args); 
} 

...

private static String UNREAD_UNSEEN_THREADID = "(read=0 OR seen=0) AND thread_id="; 

private void updateMessagesReadAndSeen(String threadId, int setRead, int setSeen) { 
    if (threadId != null && !threadId.isEmpty()) { 
     ContentValues sReadContentValues = new ContentValues(2); 
     sReadContentValues.put("read", setRead); 
     sReadContentValues.put("seen", setSeen); 

     UNREAD_UNSEEN_THREADID += threadId; 
     UpdateContent(threadUri, sReadContentValues, UNREAD_UNSEEN_THREADID, null); 
    } 
} 

我可能永遠持續下去,但是這將允許更多的靈活性,使你開發新的功能,爲您的產品向前發展。祝你好運!