我已经使用this solution为我的应用程序图标添加徽章计数器。我正在使用计数器来显示应用程序queue_table
中有多少项目正等待发送到服务器。
首先,我创建了一个MyBootReceiver
类,该类在设备启动时更新徽章计数。这部分工作正常。
我需要建议的部分是在队列更新时保持徽章计数更新的正确方法。 (可以通过应用的各个组件来更新队列-例如,从用户手动将项目添加到队列中,以及从MyIntentService
将排队的项目发送到服务器中)。
我的queue_table
可通过应用程序中的ContentProvider
进行访问,因此,我基本上需要知道的是监视此内容提供程序的更改的最佳方法(因此可以相应地更新徽章图标)。
我想知道最好的(或唯一的)解决方案是否适合我创建一个MyApplication
类,该类在其ContentObserver
方法中注册一个onCreate
-例如,
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
中进行注册? 最佳答案
我这样做的方法是在我的ContentObserver
类中使用一个MyApplication
。
如果还没有MyApplication
类,则需要通过在android:name=".MyApplication"
元素中添加<application />
属性在清单文件中指定它。
然后创建包含以下内容的MyApplication
类,如下所示:
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();
}
}
}
关于android - Android-来自内容提供商的自动更新应用程序图标徽章计数器吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35560663/