如何检测在另一个进程正在运行时以及在检测到停止该运行进程后按下的任何按钮

时间:2012-08-05 09:27:03

标签: android

  1. 我有2个按钮
  2. 当我点击后退按钮时,我推迟退出10秒
  3. 如果按下2个按钮中的任何按钮,则我想停止退出应用程序。
  4. 如果未检测到按钮,则继续退出。
  5. 公共类MainActivity扩展了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");
    
        }
    
    }
    

    }

1 个答案:

答案 0 :(得分:2)

使用Handler是您最好的解决方案。在后退时添加可通过Activity.finish()调用handler.postDelayed(yourRunnableThatCallsFinish, 10000)的runnable。请务必在按钮的onClick事件中调用handler.removeCallbacks(SameRunnableObjectThatSendToQueueViaPostDelayed)以防止执行该可运行的事件。