简体   繁体   中英

Activity gets destroyed when PowerManager.goToSleep is called

I have an activity which sometimes gets destroyed by the system as a response to PowerManager.goToSleep(...) being called. The behavior is not consistent and I can't figure out the reason for this.

Here is the relevant code for my activity's onCreate which is the most relevant part of code:

   protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);

        requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);

        IntentFilter userprsentfilter = new IntentFilter(Intent.ACTION_USER_PRESENT);
        mUserPresentReceiver = new UserPresentReceiver();
        registerReceiver(mUserPresentReceiver,userprsentfilter);

        Log.d(TAG, "created.");
    }

    protected void onDestroy() {
        Log.d(TAG, "finished.");
    }

Somewhere, on some distant service and sometimes by the activity itself,

PowerManager.goToSleep(SystemClock.uptimeMillis())

is called causing the activity the get destroyed.

Can anyone please shed some light on why the system will try to sometimes destroy an activity when PowerManager.goToSleep is called? Also, is there a way to make the sure or lower the chances of the activity getting destroyed by the system? I can say with certainty that resources are not scarce when this happens.

All Android apps are subject to being shut down at any time. This can happen when the app is backgrounded, when it is consuming too many system resources, or when the phone sleeps. You can't (and shouldn't try to) alter that behavior: it does this on purpose and for very good reasons.

If you have an operation that needs to continue running under these circumstances, you need to implement it as a Service. This will allow it to run even when the phone is sleeping.

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