0
  1. ボタンが2つあります
  2. 戻るボタンをクリックすると、終了が10秒遅れます
  3. 2つのボタンのうちいずれかのボタンが押された場合、アプリの終了を停止したいと思います。
  4. 押されたボタンが検出されない場合は、終了を続行します。

パブリッククラス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");

    }

}

}

4

1 に答える 1

2

ここでは、ハンドラーを使用するのが最善の解決策です。戻ると、handler.postDelayed(yourRunnableThatCallsFinish、10000)を介してActivity.finish()を呼び出すrunnableを追加します。そのランナブルの実行を防ぐために、ボタンのonClickイベントで必ずhandler.removeCallbacks(SameRunnableObjectThatSendToQueueViaPostDelayed)を呼び出して ください。

于 2012-08-05T09:34:21.370 に答える