简体   繁体   English

如何在 android 中停止此线程?

[英]How to stop this thread in android?

In my application i am using this thread to rotate the Second hand on the clock.在我的应用程序中,我使用这个线程来旋转时钟上的秒针。 But the Problem is while i close the activity, the thread is still remain run.但问题是当我关闭活动时,线程仍在运行。 I want to stop the thread so it can not effect the Bettry of the device.我想停止线程,这样它就不会影响设备的 Bettry。

Below is my Activity code where i am rotating the Clock's Second Hand:下面是我旋转时钟秒针的活动代码:

 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());
                }
            }
        }
    }
}

Thanks in advance.提前致谢。

try this code in your activity -在您的活动中尝试此代码 -

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

When you exit from your application, your application process is not actually destroyed.当您退出您的应用程序时,您的应用程序进程实际上并没有被销毁。 If you destroy your process, all child processes(all your child threads) will be destroyed.如果你销毁你的进程,所有子进程(所有你的子线程)都将被销毁。

Ok, that means you want to create a service that will have been running in background.好的,这意味着您要创建一个将在后台运行的服务。 One thing is that service is one type of thread, if it will run in background that will drain your device battery power.一件事是服务是一种线程,如果它在后台运行会耗尽您的设备电池电量。 So, if you kill your process then the thread as well as your service will destroy.所以,如果你杀死你的进程,那么线程和你的服务都会被破坏。 So, stop your thread like -所以,像这样停止你的线程 -

boolean running = true;

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

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

When you exit your app, the thread will stop.当您退出应用程序时,线程将停止。 And the other will stay running, that is your service.另一个将保持运行,这是您的服务。 Don't try to stop your thread forcefully, or suspend.不要试图强行停止或挂起您的线程。 It is deprecated, if your while loop of the thread breaks, then it will automatically destroy your thread according to JVM rules.它已被弃用,如果你的线程的 while 循环中断,那么它会根据 JVM 规则自动销毁你的线程。 Hope it will help you.希望它能帮助你。 Have fun...玩得开心...

don't myThread.join() on the UI thread since it will block until the Thread finished and your App might ANR.不要在 UI 线程上使用myThread.join() ,因为它会阻塞直到线程完成并且您的应用程序可能会出现 ANR。 Also Thread.currentThread().interrupt();还有Thread.currentThread().interrupt(); will try to interrupt the UI thread which is really bad.将尝试中断 UI 线程,这非常糟糕。

You can put MyThread.interrupt() in onDestroy , onPause or onStop (+ recreate the Thread in the corresponding start callback)您可以将MyThread.interrupt()放在onDestroyonPauseonStop (+在相应的启动回调中重新创建线程)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM