My app needs to launch a third-party app (Google Now) while the screen is off and the phone is locked. Right now I'm using a combination of KeyGuardManager and Wakelocks to do this, but it seems to be very unreliable only working for 50% of phones about 50% of the time. Is there a better way to do this? Is there a problem with my current code? Thanks in advance
public void activateGoogleNow() {
stopListening();
if (myAudioManager != null) {
myAudioManager.startListening();
}
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
"listen_screen_off", false)) {
final KeyguardManager keyguardManager = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
final PowerManager powerManager = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
if (!powerManager.isScreenOn()) {
WakelockManager.turnOnScreen(context);
final Handler waitForUnlock = new Handler(
new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
startGoogleNow();
return true;
}
});
new Thread(new Runnable() {
@Override
public void run() {
while (!powerManager.isScreenOn()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
}
myAudioManager.lockscreenDeactivated = true;
KeyguardLock mLock = keyguardManager
.newKeyguardLock("OpenMic");
mLock.disableKeyguard();
waitForUnlock.sendEmptyMessage(0);
}
}).start();
} else {
startGoogleNow();
}
} else {
startGoogleNow();
}
}
private void startGoogleNow() {
final Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(new ComponentName(
"com.google.android.googlequicksearchbox",
"com.google.android.googlequicksearchbox.VoiceSearchActivity"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_FROM_BACKGROUND);
context.startActivity(intent);
}
public static void turnOnScreen(Context context) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "Open Mic screen");
wl.acquire(1000);
}