AkshayT
AkshayT

Reputation: 3021

How to detect any button pressed while another process is running and after detection stoping that running process

  1. I have 2 buttons
  2. when i click back button i am delaying exit by 10 seconds
  3. if any button among 2 buttons is pressed then i want to stop exit of app.
  4. if no button pressed detected then continue exit.

public class MainActivity extends Activity {

int count=0;
boolean pressed;
Button b1,b2;
TextView t1;
Thread t;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b1= (Button) findViewById(R.id.button1);
    b2= (Button) findViewById(R.id.button2);
    t1 = (TextView) findViewById(R.id.textView2);

    b1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            pressed=true;
            t1.setText("Button1 Pressed");
            System.out.println("Button1");


        }
    });
    b2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            pressed=true;
            t1.setText("Button2 Pressed");
            System.out.println("Button2");


        }
    });
}
/* (non-Javadoc)
 * @see android.app.Activity#onBackPressed()
 */
@SuppressLint("ParserError")
@Override
public void onBackPressed() {
    System.out.println("Inside Back Button");
    pressed=false;
    t = new Thread(new ABC(), "My Thread");

    t.start();
    System.out.println("OutSide while Loop in BACKBUTTON");
    if(pressed==true){
        System.out.println("Button 1 or 2 Pressed");
        t.interrupt();
        System.out.println("Stopping Thread forcefully");

        count =0;
    }
    if(pressed==false){
        System.out.println("Button 1 or 2 NOT Pressed");
        t.stop();
        super.onBackPressed();
    }
}


public class ABC implements Runnable{



    @Override
    public void run() {
        System.out.println("Inside Thread");
        do{
            count++;
            System.out.println(count);

        }
        while((count <1000) && (pressed==false));
        System.out.println("OutSide while Loop");

    }

}

}

Upvotes: 0

Views: 365

Answers (1)

G&#246;khan Barış Aker
G&#246;khan Barış Aker

Reputation: 4545

Using Handler is your best solution here. When back pressed add runnable that calls Activity.finish() via handler.postDelayed(yourRunnableThatCallsFinish, 10000). Be sure to call handler.removeCallbacks(SameRunnableObjectThatSendToQueueViaPostDelayed) at button's onClick events to prevent execution of that runnable.

Upvotes: 2

Related Questions