在屏幕关闭且手机被锁定的情况下,通过意图启动第三方应用

时间:2013-08-04 19:19:22

标签: android android-intent android-wake-lock

我的应用需要在屏幕关闭且手机锁定时启动第三方应用(Google即时)。现在我使用KeyGuardManager和Wakelocks的组合来做到这一点,但它似乎非常不可靠,只有50%的手机在50%的时间内工作。有一个更好的方法吗?我目前的代码有问题吗?提前致谢

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);
}

1 个答案:

答案 0 :(得分:2)

我唯一不同的是添加PowerManager.FULL_WAKE_LOCK标志(这似乎至少适用于2.3和4.0手机):

pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP)