开发者

android activity running in bkground

开发者 https://www.devze.com 2023-01-14 02:14 出处:网络
is there a way to keep an activity running even though it has been sent to the background, home button is clicked, ?

is there a way to keep an activity running even though it has been sent to the background, home button is clicked, ? My app has a countdowntimer and i want the timer to keep running even though the app is in the background.

Is there a way to do this without using services ? Because ive been reading up开发者_JAVA百科 on services and im really notgetting how to use them... and if services is the only way can someone give me a simple tutorial or guide from where i can try this... I've already seen all the documents and examples on the developer.android.com website... anything apart from those...

thankyou


I have implemented small stopwatch application (for puzzle solving time measurement), and it continues to work in the background even if I press home button.

I use Handler()

mRepetitiveTimeoutHandler.postDelayed(processWatchTimer, DISPLAY_UPDATE_TIMEOUT);

to periodically call

private Runnable processWatchTimer = new Runnable()

...

Time measurement is done via comparing current time System.currentTimeMillis() each time when runnable triggers.


Handler usage example below. It will continue to work if you press Home button, but not if you press Back button. In order to achieve that, you need to use Service, as already suggested in the first answer.

import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;

public class HandlerExample extends Activity {

    private final static int DELAYED_ACTION_TIMEOUT = 10000;

    private Handler mRepetitiveTimeoutHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.example);

        mRepetitiveTimeoutHandler = new Handler();
        mRepetitiveTimeoutHandler.postDelayed(processWatchTimer, DELAYED_ACTION_TIMEOUT);                       
    }

    private Runnable processWatchTimer = new Runnable()
    {
        public void run() 
        {
            mRepetitiveTimeoutHandler.removeCallbacks(processWatchTimer);
            //Put your action here. 
        }
    };
}


Is there a way to keep an activity running even though it has been sent to the background?

No. No way at all.

If you read about the Android Lifecycle you'll find that it's pretty clear that there is no way to do this. I think part of the reason that Android makes you split your application in Activities is that it can easily free resources for Activities not being currently used.

My app has a countdowntimer and i want the timer to keep running even though the app is in the background. Is there a way to do this without using services ?

If you didn't want to use a Service you could try using the AlarmManager.

0

精彩评论

暂无评论...
验证码 换一张
取 消