简体   繁体   中英

Finish application after 15 minutes in background

How to finish application after 15 minutes, when user minimized?

When user exit from the application without finish it, then user turn back after some time network of application is not working. For work need to restart the application.

I want to trigger when the app becomes at the background and then with timer finish application.

Or how to know when the application is paused, not an activity?

Lifecycle of the application.

Solution:

Make one BaseActivity which is parent of all of your activities .

public class BaseActivity extends AppCompatActivity {
    private static Thread t = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();

        if (t != null) {
            try {
                if (t.isAlive()) {
                    t.interrupt();
                    t.join();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            t = null;
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        t = new Thread() {
            public void run() {
                try {
                    sleep(15 * 60 * 1000);
                     finishAffinity();
                    System.exit(0);
                } catch (InterruptedException e) {
                    return;
                }
            }
        };
        t.start();
    }
}

Now extends BaseActivity in all of your activity class like below sample,

public class ClassTest extends BaseActivity {
    .....
    .....
}

You need to use ProcessLifecycleOwner to check your app state. It supports library version 26+.

    //Check if app is in background
    ProcessLifecycleOwner.get().getLifecycle().getCurrentState() == 
    Lifecycle.State.CREATED;

    //Check if app is in foreground
    ProcessLifecycleOwner.get().getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED);

Here is the dependecy of ProcessLifecycleOwner . For more details visit here

dependencies {
    def lifecycle_version = "1.1.1"

    // ViewModel and LiveData
    implementation "android.arch.lifecycle:extensions:$lifecycle_version"
    // alternatively - Lifecycles only (no ViewModel or LiveData).
    //     Support library depends on this lightweight import
    implementation "android.arch.lifecycle:runtime:$lifecycle_version"
    annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" // use kapt for Kotlin
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM