An analysis of the operating mechanism of Android Surfaceview--the exception to the process of switching to the background and then back into the program _android

Source: Internet
Author: User

A lot of friends have encountered this problem, program execution switch to the background, and then re-enter the report of the exception, this article on this issue to explain the overall operation of the Surfaceview mechanism, understand these principles you can solve these problems themselves.

We usually switch to the background by clicking the Home button or by returning the button, and then we may get into the program again, and then it's possible to report an exception. There are two major surfaceview that may be reported here, as follows:

One, submit canvas exception . The following figure (emulator error prompts, and Logcat Detail)

Java code

public void Draw () {  
  try {  
    canvas = Sfh.lockcanvas ();  
    if (canvas!= null) {  
      canvas.drawcolor (color.white);  
      Canvas.drawbitmap (BMP, Bmp_x, bmp_y, paint);  
    }  
  catch (Exception e) {  
    log.v ("Himi", "Draw is error!");  
  } finally {//Memo 1  
    if (canvas!= null)/NOTE 2  
      sfh.u Nlockcanvasandpost (canvas);  
  }  

First look at note 1 here, before the article I gave you explain why to put sfh.unlockcanvasandpost (canvas); Written in finally, the main purpose is to ensure the normal submission of the canvas.

Today's main remarks 2, here must determine whether the next canvas is empty, because when the program into the background, canvas is not get! Then once the canvas is empty, the submission canvas here will have the error of abnormal parameters!

second, the thread initiates an exception. the following figure (emulator error prompts, and Logcat Detail)

This exception is only when you click the Home button in the program to enter the program again when the exception, the exception that our thread has been started! Why is the return button OK?

OK, we're going to start with a detailed explanation of the Android back and home button mechanisms! Then analyze the problem and solve the problem!

First look at the code in the Mysurfaceviewanimation.java class below:

Java code

public class Mysurfaceviewanimation extends Surfaceview implements Callback, Runnable {private Thread th;  
  Private Surfaceholder SFH;  
  Private Canvas Canvas;  
  Private Paint Paint;  
  Private Bitmap bmp;  
  private int bmp_x, bmp_y;  
    Public Mysurfaceviewanimation {Super (context);  
    This.setkeepscreenon (TRUE);  
    BMP = Bitmapfactory.decoderesource (Getresources (), r.drawable.himi_dream);  
    SFH = This.getholder ();  
    Sfh.addcallback (this);  
    Paint = new paint ();  
    Paint.setantialias (TRUE);  
    This.setlongclickable (TRUE);  
    th = new Thread (This, "Himi_thread_one");  
  LOG.E ("Himi", "mysurfaceviewanimation");  
    public void surfacecreated (Surfaceholder holder) {Th.start ();  
  LOG.E ("Himi", "surfacecreated"); public void surfacechanged (surfaceholder holder, int format, int width, int height) {log.e ("Himi", "Surfacech  
  Anged "); } public void surfacedestroyed (Surfaceholder holder) {LOG.E ("Himi", "surfacedestroyed");  
      public void Draw () {try {canvas = Sfh.lockcanvas ();  
        if (canvas!= null) {Canvas.drawcolor (color.white);  
      Canvas.drawbitmap (BMP, Bmp_x, bmp_y, paint);  
    The catch (Exception e) {log.v ("Himi", "Draw is error!");  
    finally {//memo 1 if (canvas!= null)//Memo 2 sfh.unlockcanvasandpost (canvas);  
      } public void Run () {while (true) {draw ();  
      try {thread.sleep (100);  ' Catch (Exception ex) {}}}}

The above is our commonly used custom Surfaceview, and uses the Runnable interface old frame not to say much, in which I in this class constructs, creates, the state changes, the extinction function all adds the printing!

OK, look at the first picture below: (Just run the program)

the left part of the figure above is Dubug. This shows that we have a thread running, called "Himi_thread_one."

the right part of the image above is the Logcat log . It is very clear to see that when the first entry into the program, will first enter the view constructor, and then create view, then view state changes, OK, this everyone knows!

Here's where I click on the home (small house on the phone) to press the button, and the program is in the background, and then back into the process of the program!

The diagram above shows that our thread is still one of the main observations from the click Home to the process of getting into the program again, as described below:

Click Home to call the view destroy, and then enter the program will first enter the view creation, and finally the view state change.

The above process is easy to understand, the important role of the play ~back button! Click the Back button to see what happened!

First look at the Debug column on the left, one more thread! See Logcat Discovery than click the Home button to call a constructor more than once!

Well, from the program we tested, no doubt, click Home and click the Back button to enter the program again, the steps are different, the number of threads has changed!

So this can explain why we click the back button is not unusual, click Home will be abnormal!

Reason: because click the Back button to enter the program again when the first to enter the view constructor, so that is here again a new thread out, and start! Then we click Home but not the same, because after clicking Home again into the program does not go into the constructor, but directly into the view to create this function, and in the view creation of this function we have a start thread operation, in fact, the first start of the program's thread is still running, so~ Here must be abnormal, said the thread has started!

Some children's shoes ask, why don't we put th = new Thread (This, "Himi_thread_one") in the View creation function?

Yes, you can! But when you do it several times, you find that there are many more processes in your program! (pictured below)

Although it is possible to avoid the exception that the thread has started, it is obviously not the result we want!

So here are the best solutions for you:

Modify Mysurfaceviewanimation.java:

Java code

public class Mysurfaceviewanimation extends Surfaceview implements Callback, Runnable {private Thread th;  
  Private Surfaceholder SFH;  
  Private Canvas Canvas;  
  Private Paint Paint;  
  Private Bitmap bmp;  
  private int bmp_x, bmp_y; Private Boolean Himi;  
    Note 1 public mysurfaceviewanimation {super (context);  
    This.setkeepscreenon (TRUE);  
    BMP = Bitmapfactory.decoderesource (Getresources (), r.drawable.himi_dream);  
    SFH = This.getholder ();  
    Sfh.addcallback (this);  
    Paint = new paint ();  
    Paint.setantialias (TRUE);  
    This.setlongclickable (TRUE);  
  LOG.E ("Himi", "mysurfaceviewanimation");  
    public void surfacecreated (Surfaceholder holder) {Himi = true;  
    th = new Thread (This, "himi_thread_one");//Remark 2nd.start ();  
  LOG.E ("Himi", "surfacecreated"); public void surfacechanged (surfaceholder holder, int format, int width, int height) {log.e ("Himi", "Surfacech  
  Anged ");} public void surfacedestroyed (Surfaceholder holder) {Himi = false;//Note 3 log.e ("Himi", "surfacedestroyed"  
  );  
      public void Draw () {try {canvas = Sfh.lockcanvas ();  
        if (canvas!= null) {Canvas.drawcolor (color.white);  
      Canvas.drawbitmap (BMP, Bmp_x, bmp_y, paint);  
    The catch (Exception e) {log.v ("Himi", "Draw is error!");  
    finally {if (canvas!= null) sfh.unlockcanvasandpost (canvas);  
      } public void Run () {while (Himi) {//Memo 4 draw ();  
      try {thread.sleep (100);  ' Catch (Exception ex) {}}}}

Here are the following points to be modified:

1, we all know a thread started, as long as the Run method execution end, the thread is destroyed, so I added a Boolean value of the member variable Himi (note 1), here can control the demise of our thread a switch! (Note 4)

2, before starting the thread, set this boolean value to ture, so that the thread is running.

3, when the view is destroyed, set this Boolean value to False, destroy the current thread! (Note 3)

OK, here Map and explain enough detail, I hope you really develop a game when the time, must be rigorous code, do not leave a future ha ~

Above on the Android Surfaceview operating mechanism in detail, follow-up to continue to supplement the relevant knowledge, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.