How to stop an app after some time?
Hei! In my android app I have a button that starts the app Barcode Scanner. I want to stop this app after 2 minutes, for example. How can I do this?
This is my code :
qrgame = (Button) findViewById(R.id.qrgame);
qrgame.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.setP开发者_高级运维ackage("com.google.zxing.client.android");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
});
you can finish your activity as you can start your activity using
startActivityForResult(intent, 0);
you need to pass the same requestcode to this method
finishActivity(requestCode);
for delay time you can you Thread, Timer etc.
Or you can close your opened activity just implement Timer, thread which will hold you 2 min or as per your requirement then call
finish();
You can create an asyncTask
that you execute in the onCreate
of your app. And in the AsyncTask
you write a
Thread.slepp(120000).
After that you can stop your app.
on you on create method put this code
new Thread(){
public void run(){
try{
Thread.sleep(120000);
}
catch(Exception e){}
}
}.start();
do not forget your to import the Thread or if you use elipse just CRTL+SHIFT+O
I had a similar requirement, put whatever you wish to be run in some method and call the method start and stop as such.
//Say we place a switch case for the onClickListener
case R.id.btnScan:
new CountDownTimer(120000, 120000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
stopScanning(); // Stop the application/function here
button.setText("Scanned");
}
}.start();
startScanning();
break;
精彩评论