问题
I am developing an application which should display a daydream in special circumstances, I searched everywhere to find a proper way to start my daydream service through my MainActivity class with no luck,
Currently i am using following code to start daydream and actually it works, but i need a better solution which provides me a way to stop the daydream.
public void startDayDream(){
final Intent intent = new Intent(Intent.ACTION_MAIN);
try {
// Somnabulator is undocumented--may be removed in a future version...
intent.setClassName("com.android.systemui",
"com.android.systemui.Somnambulator");
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
} catch (Exception e) { /* Do nothing */ }
}
回答1:
I'm starting it in the same way but I haven't found any official way or intent to stop the daydream.
However you can stop daydream by regaining the focus by your activity. For this purpose create a service and send any intent from your service to your activity when you want to stop daydream. As side effect your activity will come to the front when receiving intent if it was in background. This approach is working for at least Android 4.4 to 5.1.
For Android 6 it's enough to simulate a wake up in order to stop dreaming.
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "WakeUpLock");
if (wakeLock.isHeld())
wakeLock.release();
wakeLock.acquire();
wakeLock.release();
来源:https://stackoverflow.com/questions/40342372/proper-way-to-start-and-stop-daydream-service-from-activity