Example how to not losing asynctask state when rotate screen

public class MainActivity extends AppCompatActivity {
    private Async task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        task = (Async) getLastCustomNonConfigurationInstance();

        if (task == null) {
            task = new Async(this);
            task.execute();
        } else {
            task.attach(this);
        }
    }

    @Override
    public Object onRetainCustomNonConfigurationInstance() {
        task.detach();
        return task;
    }

    private static class Async extends AsyncTask<Void, Void, Void> {
        private static final String TAG = "Async";
        private Activity mActivity;
        private int counter = 0;

        public Async(Activity activity) {
            attach(activity);
        }

        @Override
        protected Void doInBackground(Void... params) {
            while (true) {
                Log.d(TAG, "doInBackground: " + "still working... " + counter++);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void detach() {
            mActivity = null;
        }

        public void attach(Activity activity) {
            mActivity = activity;
        }
    }
}

 

TIL: awake and unlock screen when installing app is possible

Here is the link:

http://stackoverflow.com/questions/22332513/wake-and-unlock-android-phone-screen-when-compile-and-run-project

Here is the answer:

One solution: set the following flags in your activity class(es):

if (BuildConfig.DEBUG) {
// These flags cause the device screen to turn on (and bypass screen guard if possible) when launching.
// This makes it easy for developers to test the app launch without needing to turn on the device
// each time and without needing to enable the "Stay awake" option.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}

These flags will:

Turn on the screen
Bypass the lock-screen
Allow showing the activity even if the device is locked

By setting those flags in your base activity, you’ll be able to continue using your application even if the device was off and/or locked at the time of running. If you try to leave your application’s process (i.e., hitting the home button, or switching to another app), the lock screen will appear, and you’ll have to manually unlock to continue using the device.

Warning: this should only be used while developing/debugging your application, so I recommend keeping the if (BuildConfig.DEBUG) check, as it is in this example