我有一个后台服务,它从服务器接收消息,并使用这些消息更新在ListView中显示的对象的内部属性。
我总是使用runOnUiThread方法运行listArrayAdapter.notifyOnDataSetChanged()命令。
由于某些原因,有时候ListView会刷新并显示属性更新,有时候则不会。
为了测试,我在我的ListView中添加了一个“刷新”按钮,当按下它时,listArrayAdapter.notifyOnDataSetChanged()被执行。
每次点击按钮时,视图都会完美地刷新。
我真的无法理解为什么尝试从服务中刷新时它不总是起作用,但我认为我可能没有始终在UIThread上运行...
我真的很绝望,希望能得到帮助。 我的代码 ServerConnectionManager.java - 扩展自Service。
我总是使用runOnUiThread方法运行listArrayAdapter.notifyOnDataSetChanged()命令。
由于某些原因,有时候ListView会刷新并显示属性更新,有时候则不会。
为了测试,我在我的ListView中添加了一个“刷新”按钮,当按下它时,listArrayAdapter.notifyOnDataSetChanged()被执行。
每次点击按钮时,视图都会完美地刷新。
我真的无法理解为什么尝试从服务中刷新时它不总是起作用,但我认为我可能没有始终在UIThread上运行...
我真的很绝望,希望能得到帮助。 我的代码 ServerConnectionManager.java - 扩展自Service。
//example of a command executed when a specific message received from the server:
//app is the Application variable
public void unFriend(int userId)
{
serverResponseManager.onUnFriend(app.getApplicationFriend(userId),false);
}
ServerResponseManager.java - 一个处理所有应用程序对服务器消息响应的类:
public void onUnFriend(FacebookUser facebookUser, boolean isYouRemovedClient) {
//this is the property which will effect the ListView view when calling the
//arrayListAdataper.notifyOnDataSetChanged();
facebookUser.setApplicationFriend(false);
app.getApplicationFriends().remove(facebookUser);
app.getDatabaseManager().deleteApplicationFriend(facebookUser.getId());
//if the application is currently running in the UI (not on the background) it will run a method inside the BaseActivity
if (app.isApplicationInForeground())
{
app.getCurrentActivity().onUnFriend(facebookUser);
if (isYouRemovedClient)
app.showToast(facebookUser.getName() + " has removed from your friends", true);
else
app.showToast(facebookUser.getName() + " has removed you from friends", true);
}
}
BaseActivity.java - 一种活动(Activity),它为扩展它的所有活动设置了所有默认配置。
//in this exemple the BaseActivity method does nothing but the ListViewActivity.java method override it
public void onUnFriend(FacebookUser facebookUser)
{
}
ListViewActivity.java - 继承自BaseActivity,并且其中有一个ListView,它应该反映在ServerResponseManager中的public void onUnFriend(FacebookUser facebookUser,boolean isYouRemovedClient)中进行的FacebookUser对象属性更改。
@Override
public void onUnFriend(FacebookUser facebookUser)
{
updateView();
}
private void updateView()
{
runOnUiThread(updateViewRunnable());
}
private Runnable updateViewRunnable()
{
Runnable run = new Runnable() {
@Override
public void run() {
listArrayAdapter.notifyDataSetChanged();
}
};
return run;
}
runOnUiThread
肯定会使传递的Runnable
在UI线程上运行。如果您发布一些代码,那将是一个好主意,因为这可能是某种并发问题。 - TrevorupdateView()
方法并不总是在你认为它应该被调用时被调用。你是否添加了一些日志来检查呢?另外,isApplicationInForeground()
和getCurrentActivity()
方法是如何实现的?使用服务而不是线程可能会改变这些方法的行为。 - David WasserBroadcastReceiver
来接收更新(您的服务应该广播而不是通知ListView)。 - Sherif elKhatib