3

我是架构组件的新手,我已经创建了一个 ViewModel 类并根据架构组件实现 LifecycleObserver,在 ViewModel 类中我有一个可运行接口的覆盖 run() 方法,并在处理程序类的帮助下延迟递归调用它,在这个值图像数组内部发生变化并被实时数据包装。

MainActivity 观察图像数组的变化,随着值的变化,ImageView 绑定图像数组的值。主活动也是生命周期的所有者。

现在我想实现生命周期观察者,这样当我暂停我的应用程序时,run() 方法也应该暂停,当我恢复应用程序时,它从我暂停的地方开始。

我通过在处理程序中创建暂停和恢复方法来尝试它,但它不起作用。

帮我解决这个问题。

MainActivity 类

private ImageViewModel imageViewModel;

private ImageView imageView;
private ProgressBar progressBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    showDialogueBox();
}

private void showDialogueBox() {
    final Dialog dialog  =  new Dialog(MainActivity.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialogue_box);
    dialog.setTitle("custom");
    Button button =(Button)dialog.findViewById(R.id.button1);
    button.setEnabled(true);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageViewModel = ViewModelProviders.of(MainActivity.this).get(ImageViewModel.class);
            subscribe();
            dialog.cancel();
        }
    });
    dialog.show();
}

private void subscribe() {
    final Observer<Integer> imageTimeObserver = new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer integer) {
            imageView = findViewById(R.id.imageView);
            imageView.setImageResource(integer);
            getLifecycle().addObserver(new BrainalyseComponent(MainActivity.this,getApplicationContext(),imageViewModel));
        }
    };

    final Observer<Integer> progressbarTimeObserver = new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer integer) {
            progressBar = findViewById(R.id.progressBar);
            progressBar.setProgress(integer);
        }
    };

    imageViewModel.getImage().observe(this,imageTimeObserver);
    imageViewModel.getProgressbarStatus().observe(this,progressbarTimeObserver);
}

视图模型类

private int imagesIndex;
private int delay;
public Handler handler;
private MutableLiveData<Integer> imageLiveData = new MutableLiveData<>();
private MutableLiveData<Integer> progressbarLiveData = new MutableLiveData<>();
private int progressBarStatus;
private HashMap<Integer,Integer> imagesAndDelay;
private int images[] =
        {
                R.drawable.food_1,
                R.drawable.food_2,
                R.drawable.food_3,
                R.drawable.food_4,
                R.drawable.food_5,
                R.drawable.food_6,
                R.drawable.food_7,
                R.drawable.food_8,
                R.drawable.food_9,
                R.drawable.food_10
        };


public ImageViewModel(){
    imagesIndex = 0;
    progressBarStatus = 0;
    delay = 2;//to be changed as delay will be discussed

    handler = new Handler();
    imagesAndDelay = new HashMap<>();

    shuffleImages();
    runnable.run();

}



private void shuffleImages() {
    Random random = new Random();
    for (int i = 0; i < images.length; i++) {
        int j = random.nextInt(images.length);
        int temp = images[i];
        images[i] = images[j];
        images[j] = temp;
    }
}



public Runnable runnable = new Runnable() {
    @Override
    public void run() {
        if (imagesIndex<images.length){
            progressBarStatus += 100/images.length;

            progressbarLiveData.postValue(progressBarStatus);
            imageLiveData.postValue(images[imagesIndex]);

            imagesAndDelay.put(images[imagesIndex],delay);

            imagesIndex++;
            delay += 2;
        }else {
            stopTask();
            return;
        }
        handler.postDelayed(runnable,2000);
    }
};


public Thread newThread = new Thread(){
    public void run(){
        if (imagesIndex<images.length){
            progressBarStatus += 100/images.length;

            progressbarLiveData.postValue(progressBarStatus);
            imageLiveData.postValue(images[imagesIndex]);

            imagesAndDelay.put(images[imagesIndex],delay);

            imagesIndex++;
            delay += 2;
        }else {
            stopTask();
            return;
        }
        try {
            sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            run();
        }
    }
};




public LiveData<Integer> getImage(){
    return imageLiveData;
}

public LiveData<Integer> getProgressbarStatus(){
    return progressbarLiveData;
}


private void stopTask() {
    delay = 2; 
    progressBarStatus = 0;
    imagesIndex = 0;
    Utility.setImagesAndDelay(imagesAndDelay);
    handler.removeCallbacks(runnable);

}

生命周期观察者

private Context mContext;
private static final String LOG_TAG = BrainalyseComponent.class.getSimpleName();
private ImageView imageView;
private ProgressBar progressBar;
private Integer integer;
LifecycleOwner lifecycleOwner;
private ImageViewModel imageViewModel;
public BrainalyseComponent(LifecycleOwner lifecycleOwner, Context context, ImageViewModel imageViewModel) {
    this.mContext = context;
    this.imageView = imageView;
    this.imageViewModel = imageViewModel;
    this.integer = integer;
    this.progressBar = progressBar;
    this.lifecycleOwner = lifecycleOwner;
}





@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume(){
    Log.d(LOG_TAG,"on resume of app");
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause(){

}
4

1 回答 1

2

您缺少侦听器,您需要在某个时候将其删除(例如从 onDestroy )

public BrainalyseComponent(LifecycleOwner lifecycleOwner, Context context, ImageViewModel imageViewModel) {
    this.mContext = context;
    this.imageView = imageView;
    this.imageViewModel = imageViewModel;
    this.integer = integer;
    this.progressBar = progressBar;
    this.lifecycleOwner = lifecycleOwner;
    lifecycleOwner.getLifecycle().addObserver(this);
}

@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy(){
    lifecycleOwner.getLifecycle().removeObserver(this);
}
于 2018-04-06T22:23:48.590 回答