Surface Created 从未被调用,因此线程从未运行?

发布于 2024-12-04 06:56:06 字数 6472 浏览 0 评论 0原文

我很长一段时间以来一直在为这个问题苦苦挣扎。我是android的新手。我已经完成了所有作业并浏览了与我的问题相关的所有主题,但这没有帮助。

我的应用程序代码基于月球着陆器并进行了修改。我有一个启动屏幕,然后显示一个菜单屏幕,启动我的主要活动。

在我的应用程序中,我有一个类游戏,我在 main.xml 中声明了该游戏,如下所示:-

我正在粘贴 xml 文件的部分:-

<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <RelativeLayout
    android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/desert"
        android:clipToPadding="true">

     <com.example.android.Game
      android:id="@+id/Game"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>

我试图从我的应用程序的 MainActivity 中扩充此活动,如下所示:-

与月球不同着陆器我的线程是与主活动不同的类。

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        mGame = (Game) findViewById(R.id.Game);
        mGameThread = mGame.getThread();

我创建了一个线程,其定义位于单独的文件中,但被声明为 Game 类的一部分。

我面临的问题是为我的 Game 类创建的表面从未被调用。因此该线程永远不会运行。

下面我粘贴游戏类

public class Game extends SurfaceView implements SurfaceHolder.Callback{

     private int mX;
     private int mY;
     private int mSpeedX;
     private int mSpeedY;
     private Bitmap mBitmap;

     private GameThread thread;

     public static Context mContext;

     private TextView mStatusText;

     private boolean mSurfaceExists;

     public Game(Context context)
     {
         super(context);
           SurfaceHolder holder = getHolder();
         holder.addCallback(this);  

         // create thread only; it's started in surfaceCreated()
         Log.w(this.getClass().getName(),"Before thread create");
         thread = new GameThread(holder, context, new Handler() {

             @Override
             public void handleMessage(Message m) {
                 Log.w(this.getClass().getName(),"In Handle message");
                  mStatusText.setVisibility(m.getData().getInt("viz"));
                    mStatusText.setText(m.getData().getString("text"));
                }


         });

         setFocusable(true); // make sure we get key events

     }

     public Game(Context context, AttributeSet attrs, int defStyle) {
         super(context, attrs, defStyle);
         SurfaceHolder holder = getHolder();
         holder.addCallback(this);  

         // create thread only; it's started in surfaceCreated()
         Log.w(this.getClass().getName(),"Before thread create");
         thread = new GameThread(holder, context, new Handler() {

             @Override
             public void handleMessage(Message m) {
                 Log.w(this.getClass().getName(),"In Handle message");
                  mStatusText.setVisibility(m.getData().getInt("viz"));
                    mStatusText.setText(m.getData().getString("text"));
                }


         });

         setFocusable(true); // make sure we get key events

     }

     public Game(Context context, AttributeSet attrs) {
         super(context, attrs);
         // register our interest in hearing about changes to our surface
         SurfaceHolder holder = getHolder();
         holder.addCallback(this);  

         // create thread only; it's started in surfaceCreated()
         Log.w(this.getClass().getName(),"Before thread create");
         thread = new GameThread(holder, context, new Handler() {

             @Override
             public void handleMessage(Message m) {
                 Log.w(this.getClass().getName(),"In Handle message");
                  mStatusText.setVisibility(m.getData().getInt("viz"));
                    mStatusText.setText(m.getData().getString("text"));
                }


         });

         setFocusable(true); // make sure we get key events

     }


     /**
         * Fetches the animation thread corresponding to this LunarView.
         * 
         * @return the animation thread
         */
        public GameThread getThread() {
            return thread;
        }



        /**
         * Standard window-focus override. Notice focus lost so we can pause on
         * focus lost. e.g. user switches to take a call.
         */
        @Override
        public void onWindowFocusChanged(boolean hasWindowFocus) {
            if (!hasWindowFocus) thread.pause();
        }

        /**
         * Installs a pointer to the text view used for messages.
         */
        public void setTextView(TextView textView) {
            mStatusText = textView;
        }

     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // TODO Auto-generated method stub
            Log.w(this.getClass().getName(),":In surface changed");
         thread.setSurfaceSize(width, height);
        }
        public void surfaceCreated(SurfaceHolder arg0) {
            // TODO Auto-generated method stub

            // start the thread here so that we don't busy-wait in run()
            // waiting for the surface to be created
            mSurfaceExists = false;

            Log.w(this.getClass().getName(),"In Surface create");
            Log.w(this.getClass().getName(),":Before starting thread at create");
            thread.setRunning(true);
            thread.start();
        }

          /*
         * Callback invoked when the Surface has been destroyed and must no longer
         * be touched. WARNING: after this method returns, the Surface/Canvas must
         * never be touched again!
         */

        public void surfaceDestroyed(SurfaceHolder arg0) {
            // TODO Auto-generated method stub
             // we have to tell thread to shut down & wait for it to finish, or else
            // it might touch the Surface after we return and explode
            boolean retry = true;
            mSurfaceExists = false;

            Log.w(this.getClass().getName(),"In Surface destroy");
            thread.setRunning(false);
            while (retry) {
                try {
                    thread.join();
                    retry = false;
                } catch (InterruptedException e) {
                }
            }



        }

I have been struggling with this issue since a long time.I am a newbie to android. I have done all the homework and gone through all the topics related to my issues but it did not help.

My app code is based on lunar lander with modifications. I have got a splash screen which then displays a menu screen which launches my main activity.

In my App, I have a claSS Game which I have declared in the main.xml as follows:-

I am pasting the portion of the xml file:-

<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <RelativeLayout
    android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/desert"
        android:clipToPadding="true">

     <com.example.android.Game
      android:id="@+id/Game"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>

I am trying to inflate this activity from my app's MainActivity as follows:-

Unlike lunar lander my thread is seperate class from the Main activity.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        mGame = (Game) findViewById(R.id.Game);
        mGameThread = mGame.getThread();

I have created a thread the definition of which is in a seperate file but but which is declared as part of Game class..

The problem I am facing is that the surfacecreated for my Game class is never called.So the thread never runs.

Below I am pasting the Game Class

public class Game extends SurfaceView implements SurfaceHolder.Callback{

     private int mX;
     private int mY;
     private int mSpeedX;
     private int mSpeedY;
     private Bitmap mBitmap;

     private GameThread thread;

     public static Context mContext;

     private TextView mStatusText;

     private boolean mSurfaceExists;

     public Game(Context context)
     {
         super(context);
           SurfaceHolder holder = getHolder();
         holder.addCallback(this);  

         // create thread only; it's started in surfaceCreated()
         Log.w(this.getClass().getName(),"Before thread create");
         thread = new GameThread(holder, context, new Handler() {

             @Override
             public void handleMessage(Message m) {
                 Log.w(this.getClass().getName(),"In Handle message");
                  mStatusText.setVisibility(m.getData().getInt("viz"));
                    mStatusText.setText(m.getData().getString("text"));
                }


         });

         setFocusable(true); // make sure we get key events

     }

     public Game(Context context, AttributeSet attrs, int defStyle) {
         super(context, attrs, defStyle);
         SurfaceHolder holder = getHolder();
         holder.addCallback(this);  

         // create thread only; it's started in surfaceCreated()
         Log.w(this.getClass().getName(),"Before thread create");
         thread = new GameThread(holder, context, new Handler() {

             @Override
             public void handleMessage(Message m) {
                 Log.w(this.getClass().getName(),"In Handle message");
                  mStatusText.setVisibility(m.getData().getInt("viz"));
                    mStatusText.setText(m.getData().getString("text"));
                }


         });

         setFocusable(true); // make sure we get key events

     }

     public Game(Context context, AttributeSet attrs) {
         super(context, attrs);
         // register our interest in hearing about changes to our surface
         SurfaceHolder holder = getHolder();
         holder.addCallback(this);  

         // create thread only; it's started in surfaceCreated()
         Log.w(this.getClass().getName(),"Before thread create");
         thread = new GameThread(holder, context, new Handler() {

             @Override
             public void handleMessage(Message m) {
                 Log.w(this.getClass().getName(),"In Handle message");
                  mStatusText.setVisibility(m.getData().getInt("viz"));
                    mStatusText.setText(m.getData().getString("text"));
                }


         });

         setFocusable(true); // make sure we get key events

     }


     /**
         * Fetches the animation thread corresponding to this LunarView.
         * 
         * @return the animation thread
         */
        public GameThread getThread() {
            return thread;
        }



        /**
         * Standard window-focus override. Notice focus lost so we can pause on
         * focus lost. e.g. user switches to take a call.
         */
        @Override
        public void onWindowFocusChanged(boolean hasWindowFocus) {
            if (!hasWindowFocus) thread.pause();
        }

        /**
         * Installs a pointer to the text view used for messages.
         */
        public void setTextView(TextView textView) {
            mStatusText = textView;
        }

     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // TODO Auto-generated method stub
            Log.w(this.getClass().getName(),":In surface changed");
         thread.setSurfaceSize(width, height);
        }
        public void surfaceCreated(SurfaceHolder arg0) {
            // TODO Auto-generated method stub

            // start the thread here so that we don't busy-wait in run()
            // waiting for the surface to be created
            mSurfaceExists = false;

            Log.w(this.getClass().getName(),"In Surface create");
            Log.w(this.getClass().getName(),":Before starting thread at create");
            thread.setRunning(true);
            thread.start();
        }

          /*
         * Callback invoked when the Surface has been destroyed and must no longer
         * be touched. WARNING: after this method returns, the Surface/Canvas must
         * never be touched again!
         */

        public void surfaceDestroyed(SurfaceHolder arg0) {
            // TODO Auto-generated method stub
             // we have to tell thread to shut down & wait for it to finish, or else
            // it might touch the Surface after we return and explode
            boolean retry = true;
            mSurfaceExists = false;

            Log.w(this.getClass().getName(),"In Surface destroy");
            thread.setRunning(false);
            while (retry) {
                try {
                    thread.join();
                    retry = false;
                } catch (InterruptedException e) {
                }
            }



        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文