2016-02-22 27 views
2

我已使用this solution爲我的應用圖標添加徽章計數器。我正在使用計數器來顯示應用程序的queue_table中有多少項正在等待發送到服務器。Android - 從內容提供商自動更新應用圖標徽章計數器?

首先,我創建了一個MyBootReceiver類,用於在設備引導時更新徽章數。這部分工作正常。

我需要建議的部分是在更新隊列時更新徽章計數的正確方法。 (隊列可以由應用程序的各種組件更新 - 例如,從用戶手動將項目添加到隊列以及從將隊列項目發送到服務器)。

queue_table是通過在應用程序中一個ContentProvider訪問,所以我基本上是需要知道的是監視更改此內容提供商(所以徽章圖標可以進行相應的更新)的最佳方式。

我想知道如果最好的(或唯一)的解決方案是爲我創造一個MyApplication類,在其onCreate方法註冊一個ContentObserver - 例如,

MyApplication.java

@Override 
public void onCreate() { 
    super.onCreate(); 

    /* 
    * Register for changes in queue_table, so the app's badge number can be updated in MyObserver#onChange() 
    */ 
    Context context = getApplicationContext(); 
    ContentResolver cr = context.getContentResolver(); 
    boolean notifyForDescendents = true; 
    myObserver = new MyObserver(new Handler(), context); 
    cr.registerContentObserver(myContentProviderUri, notifyForDescendents, myObserver); 


} 

另外,如果我確實使用這樣的解決方案,我是否需要擔心取消註冊myObserver,如果是的話,我該怎麼做MyApplication

+0

做你找到了解決辦法? – OShiffer

+0

我很確定我做到了。如果是這樣,我會在今天晚些時候更新答案。 –

+0

好的,謝謝! – OShiffer

回答

1

我這樣做的方式是在我的MyApplication類中使用ContentObserver

如果你沒有一個MyApplication類已經,您需要通過添加android:name=".MyApplication"屬性您<application />元素在你的manifest文件中指定它。

然後你創建的MyApplication類,它包含一個ContentObserver這樣的:

package com.example.myapp; 

import android.app.Application; 
import android.content.ContentResolver; 
import android.content.Context; 
import android.database.ContentObserver; 
import android.net.Uri; 
import android.os.Handler; 

public class MyApplication extends Application { 

    private static String LOG_TAG = MyApplication.class.getSimpleName(); 

    public MyApplication() { 
     super(); 
    } 

    private MyContentObserver myContentObserver = null; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 


     /* 
     * Register for changes in tables associated with myUri, so the app's badge number can be updated in MyContentObserver#onChange() 
     */ 
     myContentObserver = new MyContentObserver(new Handler(), this); 
     ContentResolver cr = getContentResolver(); 
     boolean notifyForDescendents = true; 
     Uri[] myUri = ...; 
     cr.registerContentObserver(myUri, notifyForDescendents, myContentObserver); 

    } 

    private class MyContentObserver extends ContentObserver { 

     public MyContentObserver(Handler handler, Context context) { 
      super(handler); 
     } 

     @Override 
     public void onChange(boolean selfChange) { 
      this.onChange(selfChange, null); 
     } 

     @Override 
     public void onChange(boolean selfChange, Uri uri) { 

      Utilities.updateBadgeCount(); 

     } 

    } 

} 
+0

您也可以直接從MyApplication的onCreate()調用'Utilities.updateBadgeCount();'也可以在任何內容更改之前顯示徽章。 –