3

我正在尝试根据长期运行的服务输出不断更新 UI。基本上,我想在绑定服务处理完用户列表后一一显示和附加用户列表。

MainActivityViewModel

public class MainActivityViewModel extends ViewModel {

    private MutableLiveData<User> user = new MutableLiveData<>();

    private MutableLiveData<MyService.MyBinder> mBinder = new MutableLiveData<>();
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder iBinder) {
            MyService.MyBinder binder = (MyService.MyBinder) iBinder;
            mBinder.postValue(binder);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBinder.postValue(null);
        }
    };


    public ServiceConnection getServiceConnection(){
        return serviceConnection;
    }

    public LiveData<User> getUser(){
        return user;
    }

    public LiveData<MyService.MyBinder> getBinder(){
        return mBinder;
    }
}

我的服务

public class MyService extends Service {

    private final IBinder mBinder = new MyBinder(); 
    private Handler mHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public void starFetchingUsers(User obj){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
 /**********************************************************/ 

在这里,我将一个一个地发送 POST 方法 100 次,并将作为需要是 liveData 的用户对象获得响应。因此,一旦在下一个 post 方法之后更改了此对象,我希望它在 UI 上显示或附加。

如何将此动态用户对象变量绑定到在 MainActivityViewModel 类中创建的 MutableLiveData 用户?所以这会在 UI 中自动更新。

/**********************************************************/
            }
        });

        thread.start();

    }
    public class MyBinder extends Binder{

        MyService getService(){
            return MyService.this;
        }

    }
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        stopSelf();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

请让我知道我在这两个课程中都缺少什么。

4

0 回答 0