簡體   English   中英

如何在 android 中停止此線程?

[英]How to stop this thread in 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());
                }
            }
        }
    }
}

提前致謝。

在您的活動中嘗試此代碼 -

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

當您退出您的應用程序時,您的應用程序進程實際上並沒有被銷毀。 如果你銷毀你的進程,所有子進程(所有你的子線程)都將被銷毀。

好的,這意味着您要創建一個將在后台運行的服務。 一件事是服務是一種線程,如果它在后台運行會耗盡您的設備電池電量。 所以,如果你殺死你的進程,那么線程和你的服務都會被破壞。 所以,像這樣停止你的線程 -

boolean running = true;

public void run() {
   while(running) {
       // your working code...
   }
}

@Override
protected void onDestroy() {
    running = false;
}

當您退出應用程序時,線程將停止。 另一個將保持運行,這是您的服務。 不要試圖強行停止或掛起您的線程。 它已被棄用,如果你的線程的 while 循環中斷,那么它會根據 JVM 規則自動銷毀你的線程。 希望它能幫助你。 玩得開心...

不要在 UI 線程上使用myThread.join() ,因為它會阻塞直到線程完成並且您的應用程序可能會出現 ANR。 還有Thread.currentThread().interrupt(); 將嘗試中斷 UI 線程,這非常糟糕。

您可以將MyThread.interrupt()放在onDestroyonPauseonStop (+在相應的啟動回調中重新創建線程)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM