当前位置:网站首页>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 .
边栏推荐
- yolov5目标检测神经网络——损失函数计算原理
- Unity Xlua MonoProxy Mono代理类
- iTOP-3568开发板NPU使用安装RKNN Toolkit Lite2
- Crawler (9) - scrape framework (1) | scrape asynchronous web crawler framework
- 【使用TensorRT通过ONNX部署Pytorch项目】
- Halcon 模板匹配实战代码(一)
- Wireless WiFi learning 8-channel transmitting remote control module
- 【SingleShotMultiBoxDetector(SSD,单步多框目标检测)】
- [yolov3 loss function]
- Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in
猜你喜欢
报错ModuleNotFoundError: No module named ‘cv2.aruco‘
Liunx prohibit Ping explain the different usage of traceroute
12. (map data) cesium city building map
Hiengine: comparable to the local cloud native memory database engine
你做自动化测试为什么总是失败?
abap查表程序
XML parsing
《增长黑客》阅读笔记
如何让你的产品越贵越好卖
Thoughts and suggestions on the construction of intelligent management and control system platform for safe production in petrochemical enterprises
随机推荐
Web API configuration custom route
[singleshotmultiboxdetector (SSD, single step multi frame target detection)]
【上采样方式-OpenCV插值】
【pytorch 修改预训练模型:实测加载预训练模型与模型随机初始化差别不大】
COMSOL -- three-dimensional graphics random drawing -- rotation
投资理财适合女生吗?女生可以买哪些理财产品?
如何让你的产品越贵越好卖
Which domestic cloud management platform manufacturer is good in 2022? Why?
Yolov 5 Target Detection Neural Network - Loss Function Calculation Principle
pytorch-多层感知机MLP
全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
How to make your products as expensive as possible
redis集群中hash tag 使用
Open3d European clustering
调查显示传统数据安全工具在60%情况下无法抵御勒索软件攻击
Pytorch weight decay and dropout
pytorch-权重衰退(weight decay)和丢弃法(dropout)
Principle of redis cluster mode
splunk配置163邮箱告警
无线WIFI学习型8路发射遥控模块