我有一个Android聊天应用程序,在一个名为taskfragment的片段中,有一个带有通知计数器的聊天列表。
我有一个名为chatService的类来处理通知,每当通过chatservice发出通知时,都会更新数据库以增加特定任务的通知编号。
当taskfragment打开时,它会调用一个名为refreshTasks()的函数,该函数会更新数据库中的gui。
我的问题是,如果用户处于taskfragment并且他们收到通知,我需要从聊天服务中调用refreshtasks,我该怎么做?
感谢。
答案 0 :(得分:1)
您可以将LocalBroadcastManager
用于您的目的
这个想法是在收到新消息时从服务发送广播并在你的片段上接收它
class YourService extends GcmListenerService{
@Override
public void onMessageReceived(String from, Bundle bundle) {
...
Intent pushNotification = new Intent("pushNotification");
//put any extra data using Intent.putExtra() method
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
...
}
}
现在在你的片段上收到它:
class TaskFragment extends Fragment{
private BroadcastReceiver mBroadcastReceiver;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("pushNotification")) {
// new push message is received
//update UI
handlePushNotification(intent);
}
}
};
...
}
@Override
protected void onResume() {
super.onResume();
// registering the receiver for new notification
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mBroadcastReceiver,
new IntentFilter("pushNotification"));
}
@Override
protected void onDestroy() {
//unregister receiver here
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
}
您可以参考此gist或在网上找到有关它的教程。