今天主要研究了安卓系统关于如何保持后台运行的相关方面。
package
com.eb.myapplicationsd;
import
androidx.appcompat.app.AppCompatActivity;
import
androidx.databinding.DataBindingUtil;
import
androidx.lifecycle.SavedStateViewModelFactory;
import
androidx.lifecycle.ViewModelProvider;
import
androidx.lifecycle.ViewModelProviders;
import
android.os.Bundle;
import
com.eb.myapplicationsd.databinding.ActivityMainBinding;
public
class
MainActivity
extends
AppCompatActivity {
MyViewModel myViewModel;
ActivityMainBinding binding;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding=DataBindingUtil.setContentView(
this
,R.layout.activity_main);
myViewModel = ViewModelProviders.of(
this
,
new
SavedStateViewModelFactory(getApplication(),
this
)).get(MyViewModel.
class
);
binding.setData(myViewModel);
binding.setLifecycleOwner(
this
);
}
@Override
protected
void
onPause() {
super
.onPause();
myViewModel.save();
}}
package
com.eb.myapplicationsd;
import
android.app.Application;
import
android.content.Context;
import
android.content.SharedPreferences;
import
androidx.annotation.NonNull;
import
androidx.lifecycle.AndroidViewModel;
import
androidx.lifecycle.LiveData;
import
androidx.lifecycle.SavedStateHandle;
import
androidx.lifecycle.ViewModel;
public
class
MyViewModel
extends
AndroidViewModel {
SavedStateHandle savedStateHandle;
String key=getApplication().getResources().getString(R.string.data_key);
String shpname=getApplication().getResources().getString(R.string.shp_name);
public
MyViewModel(
@NonNull
Application application,SavedStateHandle savedStateHandle) {
super
(application);
this
.savedStateHandle=savedStateHandle;
if
(!savedStateHandle.contains(key))
{
}
}
public
LiveData<Integer>getNumber()
{
return
savedStateHandle.getLiveData(key);
}
public
void
load()
{
SharedPreferences sharedPreferences=getApplication().getSharedPreferences(shpname, Context.MODE_PRIVATE);
int
x=sharedPreferences.getInt(key,
0
);
savedStateHandle.set(key,x);
}
public
void
save()
{
SharedPreferences sharedPreferences=getApplication().getSharedPreferences(shpname,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt(key,getNumber().getValue());
editor.apply();
}
public
void
add(
int
x)
{
savedStateHandle.set(key,getNumber().getValue()+x);
}}