교내 발표를 1주일 앞두고 있습니다;;
주메뉴의 구동은 가능한데 구동후에 일반 메뉴로 돌아오는것이 안됩니다.

현재는 초기메뉴에서 센서사용하는 주메뉴를 구동하고 빠져나오는 방식입니다.
일반메뉴들과 합치기전 센서사용엑티비티와 그와함께 하는 화면처리 부분만 있을때에는
액티비티를 끝내버려도 에러가 바로 뜨지 않습니다.(단, 여러번 동일 프로그램 가동시 휴대폰이 느려지는 이상한 현상 발생;;)

sensor를 주로 사용한어플리케이션인데
센서리스너와 쓰레드를 두개 사용한게 에러의 원인 같습니다.

초기메뉴화면이 나오고, 주 프로그램엑티비티를 intent면 이상없이 가동됩니다.
그런데 해당 intent에서 애플리케이션을 즐기고 나서 스마트폰 자체의 빠져나오기 화살표를 눌러서
본메뉴로 돌아오게 되면, 메뉴그림은 나오는데, 더이상 메뉴 버튼이 눌러지지 않고 멈춰있다가
십초이상 지나면 휴대폰 자체에서 강제 종료 하겠냐고 문구가 뜹니다.
그리고 종종 error obtaining an audio buffer , giving up이라는 Audiotrack으로 부터의 빨간 로그 값을 발견합니다;;
menu.PNG 

프로그램 구동을 위해 센서리스너 하나와 두개의 스레드를 사용하였습니다.
메뉴만 담당하는 엑티비티에서 버튼을 누르면, 우측화면과 같은 엑티비티를 intent시킵니다.

개략적인 코드의 모습을 보면,
메뉴만 나오는 액티비티를 제외하고
주기능 엑티비티와 화면 처리 클래스 파일은 세개의 스레드가 있습니다.
액티비티 기본 함수들 => 액티비티 생명주기 관리, sensor listener, 코드를 사용한 센서값처리, 센서처리에 이은 소리재생부분(soundpool사용)
Thread 1 => 센서리스너가 끊임없이 갱신해주는 센서값 받아와서 보정, 값처리에 따른 판단구문, 소리관련 판부분
Thread 2 => Thread1에서 수정한 화면처리 변수값들을 근거로 화면의 모양을 변경시킴


아래부터는 관련 코드와 에러 관련 Log멘트 캡쳐 부분입니다.
계속 수정하고 만들고 하다보니 코드가 많이 지저분합니다;;;

아래의 코드가 메뉴 엑티비티의 전부입니다.-----------------------
public class Screen_First extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.d("Screenfirst", "in the Screen OnCreate ");
        //모든 버튼에 클릭 리스너를 설정한다.
       
        View StartButton = this.findViewById(R.id.start_button); // 스타트 버튼
        StartButton.setOnClickListener(this);
        View howtoButton= this.findViewById(R.id.howto_button);// 게임 설명 버튼
        howtoButton.setOnClickListener(this);
        View infoButton= this.findViewById(R.id.info_button);// 게임 정보 버튼
        infoButton.setOnClickListener(this);
        View exitButton= this.findViewById(R.id.exit_button);// 끝내기 버튼
        exitButton.setOnClickListener(this); 
    }

 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  switch(v.getId()){
  case R.id.start_button:
   Intent i1 = new Intent(this, MotionPlayer.class);
   startActivity(i1);
   break;
  case R.id.howto_button:
   Intent i2 = new Intent(this, Infomation.class); // informaion 인데 클래스 이름에 오타..
   startActivity(i2);
   break;
  case R.id.info_button:
   Intent i3 = new Intent(this, Infomation.class); // informaion 인데 클래스 이름에 오타..
   startActivity(i3);
   break;
  case R.id.exit_button:
   finish();
   break;  
  } 
 }
}
--------------------------------
호출되는 엑티비티의 코드는..

public class MotionPlayer extends Activity {

       각종 상수와 변수의 선언(상세 생략)

 

       //variables for fast sound

       private SoundPool sound_pool ;

       private int[] sound_beep = new int[10];

      

       //동작판별용 쓰레드

       AngleCheckThread act = new AngleCheckThread();

      

       소켄통신을 위한 선언부분(이부분 사용전에 동일한 문제가 발생하였으므로 우선 생략)

      

 

      

        //-----             Orientation 리스너 등록------//

         private  SensorEventListener orientListener = new SensorEventListener()

           {

               public void onAccuracyChanged(Sensor sensor, int accuracy) { }

              

                    public void onSensorChanged(SensorEvent event) {

                           values = event.values;//참조변수만 전달

                          

                    }//onSensorChanged

           };

          

          

           //-----스레드를 만들어 센서값을 활용-------------------//

 

             class AngleCheckThread extends Thread{

               변수선언부분 생략..

                public void run(){

                 ..

                    ..

                       synchronized(this){

                             while(threadFlag){

                            

                

               //화면 처리를 담당하고있는 클래스의 함수를 사용하여 화면의 변화를

                       av.changeDirection(getSoundType(threadValue[0]));

                  

                            

                             synchronized(this){

센서값을 활용한 단순 처리 부분..

                             try {

                                         sleep(DELAY1);

                           } catch (InterruptedException e) {

                                         // TODO Auto-generated catch block

                                         e.printStackTrace();

                                  }

                            

                       }//end of while

                       }//end of synchronize

                 }// end of run

                 public void threadStop(){this.threadFlag=false;}

              

                

             } //end of AngleChenckThread class

             //--------------/------------------------------//

            

             //-----------센서값 처리만을 위한 함수 부분.. 스레드 사용 없음---------//

             public synchronized float[] compensate(float rawValue[]){

               float[] compensatedValue = new float[3];

             ..

               return compensatedValue;

             }

            

             //------------/-------------------------------//

             //센서값을 사용한 기타 처리부분 while 정도 외에 스레드사용 없음

             private void frontAngleSetup(){

              

               while(tempFlag){

                    ..

                      }

                     

                     

               }

              

                

             }

          

// 처리부분 단순계산 부분

    private int getSoundType(double angle)

             {

           ..

               return NO_SOUND;

             }

         

private void startMusic(int type)

              {

               ..사운드풀 사용부분

                           sound_pool.play( sound_beep[currentType], 1f, 1f, 0, 0, 1.5f );

                                 

                     } // End if

              }

   

   

            

             /** Called when the activity is first created. */

             @Override

             public void onCreate(Bundle savedInstanceState) {

              

                 super.onCreate(savedInstanceState);

                 setContentView(R.layout.bell);

                 av = (AnimateView)this.findViewById(R.id.animateview);

                

                 sm = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);

                

                

                 //variable for fast sound

                 sound_pool = new SoundPool(10, AudioManager.STREAM_MUSIC,0);

             //    sound_beep[LOW_SI] = sound_pool.load(this, R.raw.left,1);

                 //sound_beep[DO] = sound_pool.load(this, R.raw.do1,1);

                 sound_beep[RE] = sound_pool.load(this, R.raw.re1,1);

       ...

                 ..

                 sound_beep[HI_MI] = sound_pool.load(this, R.raw.hi_mi,1);

        

 

                

               //현재 Activity 보여지는 동안 화면 안꺼지게 하기               getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

                

                 /*소켓 통신을 위한 쓰레드 시작

                  * */

                 socketThread.start();

                

                

             }

            

            

              @Override

              protected void onPause() {

             

                     Log.d(tag, "in the onPause ");

                     finish();

                    

                    act.interrupt();

                          

                   

                     super.onPause();

              }

              protected void onResume() {

                     // TODO Auto-generated method stub

                     act.start();

                     super.onResume();

              }

             

              @Override

              protected void onStop() {

                     Log.d(tag, "in the onStop ");

                    

                     ListIterator<Sensor> i = listSensor.listIterator();

                

                 while(i.hasNext())

                 {

                       Sensor s = (Sensor)i.next();

                       switch(s.getType())

                       {

                      

                       case Sensor.TYPE_ORIENTATION :

                             sm.unregisterListener(orientListener, s);

                             break;

                       default:

                             break;

                       }

                 }

                 super.onStop();

              }

 

              @Override

              protected void onStart() {

                     // TODO Auto-generated method stub

                     super.onStart();

                     listSensor = sm.getSensorList(Sensor.TYPE_ALL );

                 ListIterator<Sensor> i = listSensor.listIterator();

                

                 while(i.hasNext())

                 {

                       Sensor s = (Sensor)i.next();

                       switch(s.getType())

                       {

                   

                       case Sensor.TYPE_ORIENTATION :

                             sm.registerListener(orientListener, s, SensorManager.SENSOR_DELAY_FASTEST);

                             break;

                       default:

                             break;

                       }

                 }

             

      

       }

       // 키입력 처리 부분

              public boolean onKeyDown(int keyCode, KeyEvent event) {

                     // TODO Auto-generated method stub

 

                     ..

                    

                     return super.onKeyDown(keyCode, event);

              }

      

}

//화면 처리를 담당하는 java파일 내의 코드입니다.
..........................................

 

public class AnimateView extends SurfaceView implements SurfaceHolder.Callback {

 

       private ImageThread thread;

       private TextView mStatusText;

      

       class ImageThread extends Thread{            

             private SurfaceHolder mSurfaceHolder;

             private int mDirection = 0;

 

             //----young's variable----//

             private Drawable xylophone [] = new Drawable[10];

             private int xylophoneWidth;

             private int xylophoneHeight;

             private int backgroundWidth;

             private int backgroundHeight;

            

             private int previousDirection=9, newDirection=9;

            

             public ImageThread(SurfaceHolder surfaceHolder, Context context, Handler handler){

                    mSurfaceHolder = surfaceHolder;

                    //-----young's view creating ---//

                    xylophone[0] = context.getResources().getDrawable(R.drawable.first_do);

                    xylophone[1] = context.getResources().getDrawable(R.drawable.re);

                    ..

..

             }

            

             public void run() {

            while (true) {

                Canvas c = null;

                try {

                    c = mSurfaceHolder.lockCanvas(null);

                    synchronized (mSurfaceHolder) {

                        doDraw(c);

                        //dispatchDraw(c);

//                        mVisitCount++;

                        sleep(50);//글픽만 돌릴땐 50이었음

                    }

                } catch (InterruptedException e) {

                                 // TODO Auto-generated catch block

                                 e.printStackTrace();

                           } finally {

                    // do this in a finally so that if an exception is thrown

                    // during the above, we don't leave the Surface in an

                    // inconsistent state

                    if (c != null) {

                        mSurfaceHolder.unlockCanvasAndPost(c);

                    }

                }

            }

        }//end of run

      

            

             private void doDraw(Canvas canvas) {

            // Draw the background image. Operations on the Canvas accumulate

            

                    if(previousDirection!=newDirection){

                           if (newDirection == 0){// 1

                                xylophone[0].setBounds(0, 0,xylophoneWidth ,xylophoneHeight);

                                 xylophone[0].draw(canvas);

                           }

                    ..

..

                   

        }//end of doDraw

            

             void setKeyDown(int keyCode){

                    mDirection = keyCode;

                   

             }

            

       }//class ImageThread

      

       public AnimateView(Context context, AttributeSet attrs) {

             super(context, attrs);

             // TODO Auto-generated constructor stub

             SurfaceHolder holder = getHolder();

             holder.addCallback(this);

            

             thread = new ImageThread(holder, context, new Handler(){

 

                    @Override

                    public void handleMessage(Message m) {

                           mStatusText.setVisibility(m.getData().getInt("viz"));

                mStatusText.setText(m.getData().getString("text"));

                    }

                   

             });

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

       }

 

       public void surfaceChanged(SurfaceHolder holder, int format, int width,

                    int height) {

             // TODO Auto-generated method stub

 

       }

 

       public void surfaceCreated(SurfaceHolder holder) {

             // TODO Auto-generated method stub

             thread.start();

       }

 

       public void surfaceDestroyed(SurfaceHolder holder) {

             // TODO Auto-generated method stub

             boolean retry = true;

        while (retry) {

            try {

                thread.join();

                retry = false;

            } catch (InterruptedException e) {

            }

        }     

            

       }

 

      

       public void changeDirection(int type) {

             // TODO Auto-generated method stub

             if (type == -1)

                    ;//thread.setKeyDown(0);

             else if (type == 0)

                    thread.setKeyDown(0);

       ..

       ..

       }

}


 
발생된 에러에 관련된 Log값 캡쳐 사진입니다.
error1.PNG error2.PNG
error3.PNG error4.PNG

다들 질문을 할땐 코드를 올리라고 해서 코드를 좀 올려서 너무 길이기네요..;; 나홀로 개발해 보는 터라 너무 막막해서 올립니다.