当前位置:网站首页>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 .
边栏推荐
- Error modulenotfounderror: no module named 'cv2 aruco‘
- Thoughts and suggestions on the construction of intelligent management and control system platform for safe production in petrochemical enterprises
- Install esxi 6.0 interactively
- Codeworks 5 questions per day (1700 average) - day 5
- Is investment and finance suitable for girls? What financial products can girls buy?
- Redis集群(主从)脑裂及解决方案
- 【load dataset】
- JS for循环 循环次数异常
- liunx禁ping 详解traceroute的不同用法
- How can China Africa diamond accessory stones be inlaid to be safe and beautiful?
猜你喜欢
Principle of persistence mechanism of redis
Redirection of redis cluster
Yolov5 target detection neural network -- calculation principle of loss function
Idea set the number of open file windows
【TFLite, ONNX, CoreML, TensorRT Export】
liunx禁ping 详解traceroute的不同用法
11.(地图数据篇)OSM数据如何下载使用
1 plug-in to handle advertisements in web pages
How can China Africa diamond accessory stones be inlaid to be safe and beautiful?
Reading notes of growth hacker
随机推荐
Sentinel sentinel mechanism of master automatic election in redis master-slave
[pytorch pre training model modification, addition and deletion of specific layers]
[pytorch modifies the pre training model: there is little difference between the measured loading pre training model and the random initialization of the model]
Implementation of array hash function in PHP
Redis master-slave mode
JS for循环 循环次数异常
11. (map data section) how to download and use OSM data
跨平台(32bit和64bit)的 printf 格式符 %lld 输出64位的解决方式
redis 集群模式原理
查看多台机器所有进程
【L1、L2、smooth L1三类损失函数】
无线WIFI学习型8路发射遥控模块
vscode快捷键
Liunx prohibit Ping explain the different usage of traceroute
Video networkState 属性
1个插件搞定网页中的广告
【load dataset】
ACID事务理论
Is it difficult to apply for a job after graduation? "Hundreds of days and tens of millions" online recruitment activities to solve your problems
【TFLite, ONNX, CoreML, TensorRT Export】