Why should Android development avoid delayed operations?

foreword

In development, we will more or less involve some scenarios that need to use delay operation, but delay operation is actually not a good choice, not a good solution, because it is uncontrollable and may also generate timing logic question. This time, let’s take stock of some scenarios that use delayed operations and how to avoid them. The content this time is relatively basic.

Scenes using time-lapse

When we first came into contact with development, we had basically only two brainless solutions to problems, exception capture and delay. Exception capture is easy to understand. When you encounter a crash and cannot analyze the cause, you can often bypass it by adding a try-catch, but often doing so will only lead to more difficult to troubleshoot BUG. I won't do this again, after all, the bugs prompted by the crash are easier to solve.

In fact, the delay operation is also like this. I can’t find out where the problem is, and then try it randomly, and find that adding a delay of a few seconds somewhere can make the process normal. In fact, this is the same as random addition of exception capture, which often leads to more difficult to troubleshoot problems, so if there is a problem, just calm down and solve the problem, don't try to use this method. This is also the way in which delayed operations should not occur.

Get the width and height of the view

When I first got in touch, I often didn’t get the width and height of the view correctly. I just used view.getHeight() and found that the obtained height was 0. Then I didn’t know why, so I started to try blindly, and finally tried to add a delay of 1 The altitude can be obtained in seconds.

But this is not a solution. At this time, the correct approach should be to understand the drawing process of the view, to explore why the value cannot be obtained at the beginning, and to go to the source code (of course, it is a bit difficult to blindly read the source code at the beginning), to see this What kind of mechanism is the thing, and then combine these or even other people's analysis, and then look at the source code, it is easy to see.

You can know why you should use view.post

Regular query server results

If you have an app, how do you know when you've been hijacked, when you can get messages from people, and so on. Many people often write a timer to send http requests to the server to check the status every so often. Is it okay to do this?

If you take care of the details, this is of course no problem, but have you ever heard of a protocol called websocket, you have always seen some links that do not start with http, but start with ws. Have you ever learned about a protocol called MQTT? It doesn’t matter if you haven’t. You can read my basic article: juejin.cn/post/713918… , and even rise to the level of smart hardware. Have you ever understood what IOT is?

Of course, it doesn’t mean that there is a problem with the polling request, it just needs to deal with some details, interrupts or something, and even if there is a better way to achieve the effect you want, why not use a better one?

But if you want to perform some local tasks regularly, there is no problem with using a timer. The key is to handle some details, life cycle, interrupt operation, pause operation, etc.

broadcast order

In complex multi-application situations, broadcasts are often used more or less. In fact, there is a sequence problem in the registration of broadcasts and the sending of broadcasts. It is possible that some of your logic causes the broadcast to be sent first, and then the other side registers, then there will be a situation where the broadcast cannot be received. In order to deal with this problem simply, some people often add a delay to delay the sending of the broadcast.

Then this is actually a very dangerous operation. The correct way is to have a certain understanding of broadcasting. You will know that there is a type of broadcast called sticky broadcast. Even if you are familiar with the knowledge in this field, you still don’t understand it or it is not applicable to you in this scene, then you will have a better way to solve this problem. problem, not by delaying this unsafe operation.

delayed initialization

We all know that it is not good to do too many initialization operations in Application or in onCreate. We all know optimization and optimization of startup speed, so we will not do initialization in these places. Then some people will come up with some tricks, I will add a delay in these places, delay for a second or two and then initialize, so as to optimize the startup speed and initialize before the corresponding function is used, isn’t it? Beautiful? What do you think

What is the principle of your delay, the handler mechanism, do you know something called IdleHandler?

In fact, using IdleHandler alone is not a safe operation, so why not initialize the function when it is used for the first time? Some people may say that if initialization is a time-consuming operation, it will affect the user experience if it is initialized when it is used for the first time. For this problem, I usually use it together, and initialize it in IdleHandler, and then initialize it if it is judged that it has not been initialized when it is used for the first time. Special circumstances can be carried out in some places, depending on specific needs.

Scenes using time-lapse

Since delay is such a dangerous operation, and there are generally better ways to replace it, should we kill it without using delay operation? No, sometimes it’s really not good to not use it, so when do you need to use it? Of course, there is no way to solve this problem through other methods. Use it, but use it with care.

For example, if I call someone else's library, that library does an operation, and then calls me back. This is a basic process. However, this library is not yours. Maybe he wrote a BUG or some other reason, causing you to call his method, but he does not give you a callback. In this case, if you don't do anything, you will always be stuck here.

So for this situation, a timeout mechanism is generally used to make the process safer. For example, if you don't call me back for 20 seconds, I will return failure. Of course, I think that we should first communicate with the author of the library about this problem. There is really no other way, so I use this kind of trick.

But if you do this, pay attention to the status, for example, you have timed out, what if he calls you back at this time? So with this method, you need to write a lot of things to ensure its safety.

Another situation is Loading, which I may have operated a lot since before. When loading, I will not display the chrysanthemum immediately, but will display it after a delay of 0.5 seconds, so that I can have a better experience.

Of course, you want to write a delay first, and then after a few versions you tell your boss, I want to optimize, and then you remove the delay, see if it is obviously faster, if you want to play like this , then pretend I didn't say it.

In addition, you are also particular about the delay. For example, I do some operations after redrawing and updating the page after the page is displayed. Then how do I do it? The system has a way to achieve it. If you say I will do a delay ( I am here to give an example), then you need to know that the screen refresh is 16ms, but if the drawing is not finished, it will be put on the next refresh, for safety, you can set it higher, you can set a delay of 80ms, but there is no It needs to be set to a second or two.

Be careful with delays

Why do you say that you should try to avoid using delay operations, because this operation is indeed full of pitfalls, and most of the delay operations in Android will be implemented with postDelayed.

First of all, you have to consider a problem, the interruption problem, you need an interruption mechanism, for example, you have performed a delay operation in the Activity, but the Activity is destroyed, and you still need to continue to perform the operation when the delay time is up? So the Handler message will be removed in the Activity's onDestroy.

Let's say you add interrupts, but is it safe to do just that? Have you ever considered that when you interrupt, the message has already started processing. So at this time, it is necessary to use a state to make a judgment. According to this state, it is judged whether the Activity is destroyed. If it is consumed, the subsequent operations will not be performed.

Here is just one of the scenarios. In fact, it is often dangerous to use delay time, so you need to be cautious when using it. If you can use it, you don’t need it. If you must use it, you need to think carefully.

share readers

The author switched from java to Android development in 2013. He has worked in a small factory, as well as in large factories such as Huawei and OPPO. He joined Ali in April 2018 until now.

Been interviewed, and interviewed a lot of people. I know that most junior and middle-level Android engineers want to improve their skills, and they often grope and grow by themselves. The unsystematic learning effect is inefficient and long, and it is easy to hit the ceiling and stagnate in technology!

We have compiled a complete set of learning materials for Ali P7-level Android architects, especially suitable for in-depth study and improvement of small partners with more than 3-5 years of experience.

It mainly includes Tencent, as well as ByteDance, Alibaba, Huawei, Xiaomi, and other first-line Internet companies' mainstream architecture technologies. If you need it, just take it.

Tencent T3 architect learning special materials

If you feel that your learning efficiency is low and you lack correct guidance, you can scan the QR code below and join a technical circle with rich resources and a strong learning atmosphere to learn and communicate together!

In the group, there are many front-line technology giants, as well as code farmers working in small factories or outsourcing companies. We are committed to creating an equal, high-quality Android communication circle. It may not be possible to make everyone's technology advance by leaps and bounds in the short term, but from In the long run, vision, pattern, and the direction of long-term development are the most important.

Most of the middle-aged crisis at the age of 35 is due to being led away by short-term interests, and the value is squeezed out prematurely. If you can establish a correct long-term career plan from the beginning. After the age of 35, you will only be worth more than the people around you.

Guess you like

Origin blog.csdn.net/Eqiqi/article/details/130268805