How to stop an app after some time?

2019-12-16 17:32发布

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.setPackage("com.google.zxing.client.android");
                intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                startActivityForResult(intent, 0);
            }
        });

4条回答
何必那么认真
2楼-- · 2019-12-16 17:46

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();
查看更多
戒情不戒烟
3楼-- · 2019-12-16 18:03

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.

查看更多
乱世女痞
4楼-- · 2019-12-16 18:05

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;  
查看更多
Lonely孤独者°
5楼-- · 2019-12-16 18:09

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

查看更多
登录 后发表回答