当前位置:网站首页>MVVM framework part I lifecycle
MVVM framework part I lifecycle
2022-07-05 11:57:00 【asahi_ xin】
One .LifeCycle Introduce
Decoupling plays an important role in software development , Normal components need to rely on the life cycle of system components in the process of use . stay onCreate or onResume Method initialization , stay onPause Stop in , stay onDestroy Resource recycling in . This may cause memory leaks .LifeCycle It was born for this , You can strengthen the management of custom components , Callback methods that do not depend on the page lifecycle .
Two . Easy to use
Many of our needs are in onResume To initialize ,onPause To stop . Such as NFC Or get the geographical location
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
Log.d("=====","onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.d("=====","onPause");
}
}
Jetpack Provide us with two classes ,LifecycleOwner( Observed ) and LifecycleObserver( The observer ).
Activity It's done LifecycleOwner Interface , We just need to achieve LifecycleObserver that will do .
public class MyMainListener implements LifecycleObserver {
private OnMainChangeListener listener;
public MyMainListener(OnMainChangeListener listener) {
this.listener = listener;
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
private void myResume() {
listener.onChange("onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
private void myPause() {
listener.onChange("onPause");
}
public interface OnMainChangeListener {
void onChange(String message);
}
}
Use... In method @OnLifecycleEvent(Lifecycle.Event.ON_XXX) Label for identification . When the life cycle changes periodically , Method will automatically call .
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyMainListener listener = new MyMainListener(new MyMainListener.OnMainChangeListener() {
@Override
public void onChange(String message) {
Log.d("=====", message);
}
});
getLifecycle().addObserver(listener);
}
}
stay service aspect ,Android Provide LifecycleService, Inheritance of such kind Service, Realization LifecycleOwner Interface , Usage and Activity similar .
Add dependency
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
public class MyServiceObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
private void myCreate() {
Log.d("=====", "create");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
private void destroy() {
Log.d("=====", "destroy");
}
}
public class MyService extends LifecycleService {
public MyService() {
MyServiceObserver myServiceObserver = new MyServiceObserver();
getLifecycle().addObserver(myServiceObserver);// Add observers
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.start).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
});
findViewById(R.id.stop).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
}
3、 ... and .ProcessLifecycleOwner
There are also system components with a lifecycle Application.Android It also provides ProcessLifecycleOwner To monitor the application lifecycle .
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
public class ApplicationObserver implements LifecycleObserver {
/** * ON_CREATE It will only be called once in the entire life cycle of the application */
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.d("=====", "Lifecycle.Event.ON_CREATE");
}
/** * When the application appears in the foreground, call */
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.d("=====", "Lifecycle.Event.ON_START");
}
/** * When the application appears in the foreground, call */
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.d("=====", "Lifecycle.Event.ON_RESUME");
}
/** * Called when the application exits to the background */
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.d("=====", "Lifecycle.Event.ON_PAUSE");
}
/** * Called when the application exits to the background */
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.d("=====", "Lifecycle.Event.ON_STOP");
}
/** * Will never be called to , The system does not distribute calls ON_DESTROY event */
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.d("=====", "Lifecycle.Event.ON_DESTROY");
}
}
public class BaseApp extends Application {
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(new ApplicationObserver());
}
}
With ProcessLifecycleOwner, We can monitor the application lifecycle , But there are a few points to note .
- ProcessLifecycleOwner It is the monitoring of the whole application , And Activity The quantity of is irrelevant .
- ON_CREATE It will only be called once ,ON_DESTROY Although there are methods, they will not call .
边栏推荐
- COMSOL -- establishment of 3D graphics
- 【pytorch 修改预训练模型:实测加载预训练模型与模型随机初始化差别不大】
- Yolov 5 Target Detection Neural Network - Loss Function Calculation Principle
- Web API configuration custom route
- Dynamic SQL of ibatis
- Halcon 模板匹配实战代码(一)
- 查看rancher中debug端口信息,并做IDEA Remote Jvm Debug
- Troubleshooting of high memory usage of redis in a production environment
- ACID事务理论
- XML解析
猜你喜欢

pytorch-权重衰退(weight decay)和丢弃法(dropout)

liunx禁ping 详解traceroute的不同用法

12. (map data) cesium city building map

yolov5目標檢測神經網絡——損失函數計算原理

【SingleShotMultiBoxDetector(SSD,单步多框目标检测)】

Simply solve the problem that the node in the redis cluster cannot read data (error) moved

【PyTorch预训练模型修改、增删特定层】

12.(地图数据篇)cesium城市建筑物贴图

13.(地图数据篇)百度坐标(BD09)、国测局坐标(火星坐标,GCJ02)、和WGS84坐标系之间的转换

11.(地图数据篇)OSM数据如何下载使用
随机推荐
Redirection of redis cluster
Project summary notes series wstax kt session2 code analysis
Application of a class of identities (vandermond convolution and hypergeometric functions)
[yolov3 loss function]
Linux Installation and deployment lamp (apache+mysql+php)
Pytorch MLP
Linux安装部署LAMP(Apache+MySQL+PHP)
[calculation of loss in yolov3]
[pytorch modifies the pre training model: there is little difference between the measured loading pre training model and the random initialization of the model]
[untitled]
How can China Africa diamond accessory stones be inlaid to be safe and beautiful?
Yolov5 target detection neural network -- calculation principle of loss function
Multi table operation - Auto Association query
Thoughts and suggestions on the construction of intelligent management and control system platform for safe production in petrochemical enterprises
Pytorch linear regression
【load dataset】
1.php的laravel创建项目
XML解析
COMSOL -- three-dimensional graphics random drawing -- rotation
Shell script file traversal STR to array string splicing