DUPLICATE WARNING: this problem is for both services and frontends, there are some similar threads but focused on GUI approaches.
Problem
Starting from whatever the state is (music playing in the background, screen on (sic!), screen off, phone locked, phone unlocked, and so on) I would like to change only one thing in the state -- turn the screen on. Nothing else should change.
Attempts
To start from some known state I lock the phone and turn the screen off:
DevicePolicyManager dpm = (DevicePolicyManager)context
.getSystemService(Context.DEVICE_POLICY_SERVICE);
dpm.lockNow();
so from now on, turning on screen would mean actually displaying the keyguard. I try to do this with:
- forcing
userActivity
-- nothing happens at all - various combinations of wake locks -- either wake is too weak (like
PARTIAL_WAKE_LOCK
-- nothing happens) or it triggers screen on, but as long as I keep the lock. Once I release it the screen goes back to off state (despite I haveON_AFTER_RELEASE
set); minor problem is I have to acquire wake lock with some delay afterlockNow
because otherwiselockNow
would be simply canceled
Workaround
This is almost copy&paste from Changing the Screen Brightness System Setting Android by Anton Cherkashyn
You need to add fake activity which triggers screen on:
public class DummyBrightnessActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
//this next line is very important, you need to finish your activity with slight delay
new Handler().postDelayed(new Runnable() {
public void run() {
DummyBrightnessActivity.this.finish();
} },0);
}
}
Next you have to launch this activity (in my case it is usually non-activity, thus option for background):
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(context, DummyBrightnessActivity.class);
intent.addFlags(Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} },500);
And you have to notify your app about this fake activity in your manifest:
<activity android:name=".DummyBrightnessActivity"
android:excludeFromRecents="true"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:taskAffinity="com.antonc.phone_schedule.Dummy">
</activity>
(above -- it is placed in the main namespace of my app).
The problem is it is lengthy and not reliably -- the first delay (in activity) works for 0 quite fine, but the second... different story, when I did some logging "350" were enough, but once I dropped logging (thus execution was tad faster) I had to increase the value.
So now face the fact that you have "screenOn" feature, but it won't work, because some user will buy faster phone ;-)
Anyway, still looking for something better...