Siten
Siten

Reputation: 4533

android thread still running after pressing back button

I want to stop a thread when a back button is pressed.
I'm using Handler.

Upvotes: 5

Views: 6651

Answers (6)

Abhilash
Abhilash

Reputation: 507

If you are using handler you can just remove the callbacks by handler.removeCallbacks(runnable); This Should perfectly work. Happy Coding :)

Upvotes: 0

Nirav Dangi
Nirav Dangi

Reputation: 3647

Here is a demo to stop the thread an easier and faster way.

Button back = (Button)findViewById(R.id.back);
back.setText("Back");
back.setOnClickListener(this);

private Handler handler = new Handler() 
{
@Override
    public void handleMessage(Message msg) 
    {
        super.handleMessage(msg);
        if(msg.obj.toString().contentEquals("hello"))
        {
            // do whatever u what to perform after thread stop....
        }
        removeDialog(0);
        }
 };

@Override
public void onClick(View v) 
{
    if(v==back)
    {   
        showDialog(0);
        t=new Thread()
        {
            public void run()
            {
                Message toMain = handler.obtainMessage();
                toMain.obj = "hello";
                handler.sendMessage(toMain); 
            }
        };          
        t.start();
    }
}

@Override
protected Dialog onCreateDialog(int id) 
{
             switch (id) 
        {
                    case 0: 
            {
                          ProgressDialog dialog = new ProgressDialog(this);
                          dialog.setMessage("Connecting . . . . . .");
                          dialog.setIndeterminate(true);
                          dialog.setCancelable(true);
                          return dialog;
                    } 
              }
              return null;
}

Use this method to create or stop the thread. I hope that it would take less time.

Upvotes: 0

Ujwal Parker
Ujwal Parker

Reputation: 682

Store a reference to the thread when you create it. In your activity's onPause, pause or kill the reference thread.

Upvotes: 1

Vicky Kapadia
Vicky Kapadia

Reputation: 6081

You can assign an action on back button press by overriding the onBackPressed() function in your activity. This action must have a command to stop the thread. It will appear as below.

@Override
public void onBackPressed() {
    super.onBackPressed();
             thread.stop();
}

Upvotes: 0

Uday
Uday

Reputation: 6023

You can't use either stop or destroy methods. In the onStop method you have to use this.

Upvotes: 2

Wroclai
Wroclai

Reputation: 26925

You need to use Handler's removeCallbacks() function.

Sample code:

@Override
public boolean onBackPress(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        handler.removeCallbacks(yourRunnable);
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

Upvotes: 2

Related Questions