如何定期运行方法,但仅在应用程序打开时?
即使应用程序从一个活动转换到另一个活动,这仍应继续有效。
警报似乎不会对我有用,因为即使应用程序已关闭,它仍会继续。
答案 0 :(得分:1)
我会建议调查绑定服务(即使应用程序不在屏幕上也能正常运行)
http://developer.android.com/guide/components/bound-services.html
答案 1 :(得分:1)
您可以在onStart
中初始化Thread并在onStop
中清除它,以确保它仅在活动开启时运行。然后,您的工作将在新线程上进行,请注意,在使用线程时,如果不与主线程进行通信,则无法更新UI。
要确保在所有活动中都发生这种情况,请考虑从“活动”继承,覆盖onStart
和onStop
,然后让所有活动继承该活动。
编辑:
确定应用关闭的时间很棘手,取决于您的应用的工作方式。我在一个常见的Activity中使用以下代码解决了这个问题。
@Override
protected void onStart() {
super.onStart();
if(mUserNavigatedAwayFromApp) {
mUserNavigatedAwayFromApp = false;
// Stop Thread or whatever you need to do here
}
// In case we resume without stopping after starting another activity (e.g. if the newer activity is transparent)
// We need to clear this flag for the next call to onStop
mOnStopPredicted = false;
}
private boolean mOnStopPredicted = false;
private boolean mUserNavigatedAwayFromApp = false;
@Override
public void startActivityForResult(Intent intent, int resultCode) {
// User is navigating forward, set this flag so that onStop does not log out the user
mOnStopPredicted = true;
super.startActivityForResult(intent, resultCode);
};
@Override
public void finish() {
// User is navigating backward, set this flag so that onStop does not log out the user
mOnStopPredicted = true;
super.finish();
};
@Override
protected void onStop() {
// We track when know about activity navigation and if the activity stops WITHOUT us knowing about it
if(mOnStopPredicted == false) {
mUserNavigatedAwayFromApp = true;
}
mOnStopPredicted = false;
super.onStop();
}
此问题中的某些解决方案可能更适合您的需求How to detect when an Android app goes to the background and come back to the foreground。
答案 2 :(得分:0)
您可以启动Sticky Service并在该服务中创建处理程序。然后,您可以将runnable发布到Handler,如下所示:
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override public void run() { // run repeating code here
handler.postDelayed(this, 5000); // delay 5s
}
}
handler.post(runnable);