1

Вопрос по multithreading, android – Как остановить эту тему в Android?

В моем приложении я использую эту тему, чтобы вращать секундную стрелку на часах. Но проблема в том, что пока я закрываю действие, поток все еще остается запущенным. Я хочу остановить поток, чтобы он не мог повлиять на Bettry устройства.

Ниже приведен код моей активности, где я вращаю секундную стрелку часов:

 public class ClockActivity extends Activity implements OnClickListener{
    private Button chimeBtn;
    private ImageView img;
    private Thread myThread = null;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.clock_layout);


        Runnable runnable = new CountDownRunner();
        myThread = new Thread(runnable);
        myThread.start();

        chimeBtn = (Button) findViewById(R.id.chimeBtn);
        chimeBtn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.chimeBtn:
                playSound(R.raw.one_bell);
                break;
        }
    }
    public void playSound(int resources){

         MediaPlayer mp = MediaPlayer.create(getApplicationContext(), resources);
            mp.start();


    }

    private void doPlay(){
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                Log.v("log_tag", "this is seocond thread");

            }
        }).start();
    }
    public void doRotate() {

        runOnUiThread(new Runnable() {
            public void run() {
                try {

                    Date dt = new Date();
                    int hours = dt.getHours();
                    int minutes = dt.getMinutes();
                    int seconds = dt.getSeconds();
                    String curTime = hours + ":" + minutes + "::" + seconds;
                    Log.v("log_tag", "Log is here Time is now" + curTime);
                    img = (ImageView) findViewById(R.id.imgsecond);
                    RotateAnimation rotateAnimation = new RotateAnimation((seconds - 1) * 6, seconds * 6,
                            Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);

                    rotateAnimation.setInterpolator(new LinearInterpolator());
                    rotateAnimation.setFillAfter(true);

                    img.startAnimation(rotateAnimation);
                } catch (Exception e) {
                    Log.e("log_tag", "Error msg is " + e.toString());

                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) { 

        if (keyCode == KeyEvent.KEYCODE_BACK) {       
            System.out.println("Back Key Press");
            if (myThread != null) {

                   myThread.interrupt(); //says that the myThread should stop 
                   try{ 
                           myThread.join(); //make this myThread wait for the other myThread to  finish before returning
                           myThread = new Thread();
                           myThread = null;
                   }catch(InterruptedException ie){ 
                           //handle the case if the thread.join is interrupt 
                           //don't know if this will ever happen, if it can... throw a runtime exception?, or reinterrupt? 
                           Thread.currentThread().interrupt(); 
                           //   reinterrupt because thrown exception cleared interrupt and hope it's handled elsewhere 
                   } 

            }
            System.out.println("Back Key Press");
            return true;       
        }       
        return super.onKeyDown(keyCode, event);     
    } 

    @Override
    public void onDestroy(){

        System.out.println("OnDestroy");

        super.onDestroy();

    }

    class CountDownRunner implements Runnable {
        // @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    // Log.v("log_tag", "Roate is going");
                    doRotate();
                    Thread.sleep(1000);
                    //doPlay();
                    } catch (InterruptedException e) 
                    {
                    // Thread.currentThread().interrupt();
                } catch (Exception e) {
                    Log.e("log_tag", "Error is " + e.toString());
                }
            }
        }
    }
}

Заранее спасибо.

  • Error: User Rate Limit Exceeded

    от iDroid Explorer
  • Error: User Rate Limit Exceededcatch (InterruptedException e)Error: User Rate Limit ExceededisInterrupted()Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededreturn;Error: User Rate Limit ExceededLog.d()Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от iDroid Explorer
  • Error: User Rate Limit Exceeded

    от iDroid Explorer
  • Error: User Rate Limit Exceeded

    от iDroid Explorer
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от iDroid Explorer
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от iDroid Explorer
  • 5

    Error: User Rate Limit Exceeded

    @Override
    protected void onDestroy() {
        android.os.Process.killProcess(android.os.Process.myPid());
    }
    

  • 3

    Error: User Rate Limit Exceeded

    myThread.join()Thread.currentThread().interrupt();

    MyThread.interrupt()onDestroy, onPauseonStop

  • 4

    Error: User Rate Limit Exceeded

    boolean running = true;
    
    public void run() {
       while(running) {
           // your working code...
       }
    }
    
    @Override
    protected void onDestroy() {
        running = false;
    }