android-将程序Activity保留(防止被后台自动删除)

为了将程序的数据保留,防止程序在后台被后台自动销毁。可以使用
SavedStateVMFactory来使得程序数据得到保留
若要使用这种方法需要在build.gradle里面添加
implementation ‘androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha01’
android-将程序Activity保留(防止被后台自动删除)_第1张图片
我这里使用了Binding来控制UI交互
MainActivity
重点在myViewModel= …那一行

package com.example.applicationtest00;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.SavedStateVMFactory;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import android.os.Bundle;
import android.os.PersistableBundle;

import com.example.applicationtest00.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;
    MyViewModel myViewModel;
    public final static String KEY_NUMBER = "my_number";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        myViewModel = ViewModelProviders.of(this,new SavedStateVMFactory(this)).get(MyViewModel.class);
        binding.setData(myViewModel);
        binding.setLifecycleOwner(this);
    }


}

ViewModelTest类

package com.example.applicationtest00;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.ViewModel;

public class MyViewModel extends ViewModel {
    public SavedStateHandle handle;
    public MyViewModel(SavedStateHandle handle){
        this.handle = handle;
    }

    public MutableLiveData<Integer> getMyitem() {
        if(!handle.contains(MainActivity.KEY_NUMBER)){
            handle.set(MainActivity.KEY_NUMBER,0);
        }
        return handle.getLiveData(MainActivity.KEY_NUMBER);
    }
    public void Add(){
        this.getMyitem().setValue(this.getMyitem().getValue()+1);
    }
}

Layout
重点在 android:text=
还有

你可能感兴趣的:(Android,JAVA)