App's Latency

Asked 2 years ago, Updated 2 years ago, 28 views

There are three activities in the app I'm creating: A->B->C->A. Regardless of the current activity, if the app is dormant for 15 minutes, you want to detect it and display a message. What is the best way to do this?

android

2022-09-22 14:53

1 Answers

I think I'd use this method :

Class that stores global threads that manage downtime

public class ControlApplication extends Application
{
    private static final String TAG=ControlApplication.class.getName();
    private waiter; // Threads that control idle time

    // Only non-urgent initialization takes place here!
    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.d(TAG, "Starting application"+this.toString());
        waiter=new Waiter(15*60*1000); //15 mins
        waiter.start();
    }

    public void touch()
    {
        waiter.touch();
    }
}

Class to be used as parent of all activities

public class ControlActivity extends Activity
{
    private static final String TAG=ControlActivity.class.getName();

    /**
     * * Gets reference to global Application
     * * @return must always be type of ControlApplication! See AndroidManifest.xml
     */
    public ControlApplication getApp()
    {
        return (ControlApplication )this.getApplication();
    }

    @Override
    public void onUserInteraction()
    {
        super.onUserInteraction();
        getApp().touch();
        Log.d(TAG, "User interaction to "+this.toString());
    }

}

Finally, threads that manage downtime.

public class Waiter extends Thread
{
    private static final String TAG=Waiter.class.getName();
    private long lastUsed;
    private long period;
    private boolean stop;

    public Waiter(long period)
    {
        this.period=period;
        stop=false;
    }

    public void run()
    {
        long idle=0;
        this.touch();
        do
        {
            idle=System.currentTimeMillis()-lastUsed;
            Log.d(TAG, "Application is idle for "+idle +" ms");
            try
            {
                Thread.sleep (5000); //Check every 5 seconds
            }
            catch (InterruptedException e)
            {
                Log.d(TAG, "Waiter interrupted!");
            }
            if(idle > period)
            {
                idle=0;
                //Insert code here, such as calling a pop-up.
            }
        }
        while(!stop);
        Log.d(TAG, "Finishing Waiter thread");
    }

    public synchronized void touch()
    {
        lastUsed=System.currentTimeMillis();
    }

    public synchronized void forceInterrupt()
    {
        this.interrupt();
    }

    //Stop the Thread
    public synchronized void stop()
    {
        stop=true;
    }

    public synchronized void setPeriod(long period)
    {
        this.period=period;
    }

}


2022-09-22 14:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.