auto import from //depot/cupcake/@135843

This commit is contained in:
The Android Open Source Project
2009-03-03 18:28:48 -08:00
parent fee49fc0d2
commit 10bf778e49
26 changed files with 0 additions and 9768 deletions

View File

@@ -1,13 +0,0 @@
LOCAL_PATH:= $(call my-dir)
# the library
# ============================================================
include $(CLEAR_VARS)
LOCAL_SRC_FILES := \
$(call all-subdir-java-files)
LOCAL_MODULE := android.policy_phone
LOCAL_UNINSTALLABLE_MODULE := true
include $(BUILD_JAVA_LIBRARY)

View File

@@ -1,215 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import com.android.internal.R;
import com.android.internal.widget.LockPatternUtils;
import android.accounts.AccountsServiceConstants;
import android.accounts.IAccountsService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Rect;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.Editable;
import android.text.InputFilter;
import android.text.LoginFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* When the user forgets their password a bunch of times, we fall back on their
* account's login/password to unlock the phone (and reset their lock pattern).
*
* <p>This class is useful only on platforms that support the
* IAccountsService.
*/
public class AccountUnlockScreen extends RelativeLayout implements KeyguardScreen,
View.OnClickListener, ServiceConnection, TextWatcher {
private static final String LOCK_PATTERN_PACKAGE = "com.android.settings";
private static final String LOCK_PATTERN_CLASS =
"com.android.settings.ChooseLockPattern";
/**
* The amount of millis to stay awake once this screen detects activity
*/
private static final int AWAKE_POKE_MILLIS = 30000;
private final KeyguardScreenCallback mCallback;
private final LockPatternUtils mLockPatternUtils;
private IAccountsService mAccountsService;
private TextView mTopHeader;
private TextView mInstructions;
private EditText mLogin;
private EditText mPassword;
private Button mOk;
private Button mEmergencyCall;
/**
* AccountUnlockScreen constructor.
*
* @throws IllegalStateException if the IAccountsService is not
* available on the current platform.
*/
public AccountUnlockScreen(Context context,
KeyguardScreenCallback callback,
LockPatternUtils lockPatternUtils) {
super(context);
mCallback = callback;
mLockPatternUtils = lockPatternUtils;
LayoutInflater.from(context).inflate(
R.layout.keyguard_screen_glogin_unlock, this, true);
mTopHeader = (TextView) findViewById(R.id.topHeader);
mInstructions = (TextView) findViewById(R.id.instructions);
mLogin = (EditText) findViewById(R.id.login);
mLogin.setFilters(new InputFilter[] { new LoginFilter.UsernameFilterGeneric() } );
mLogin.addTextChangedListener(this);
mPassword = (EditText) findViewById(R.id.password);
mPassword.addTextChangedListener(this);
mOk = (Button) findViewById(R.id.ok);
mOk.setOnClickListener(this);
mEmergencyCall = (Button) findViewById(R.id.emergencyCall);
mEmergencyCall.setOnClickListener(this);
Log.v("AccountUnlockScreen", "debug: Connecting to accounts service");
final boolean connected = mContext.bindService(AccountsServiceConstants.SERVICE_INTENT,
this, Context.BIND_AUTO_CREATE);
if (!connected) {
Log.v("AccountUnlockScreen", "debug: Couldn't connect to accounts service");
throw new IllegalStateException("couldn't bind to accounts service");
}
}
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
mCallback.pokeWakelock(AWAKE_POKE_MILLIS);
}
@Override
protected boolean onRequestFocusInDescendants(int direction,
Rect previouslyFocusedRect) {
// send focus to the login field
return mLogin.requestFocus(direction, previouslyFocusedRect);
}
/** {@inheritDoc} */
public boolean needsInput() {
return true;
}
/** {@inheritDoc} */
public void onPause() {
}
/** {@inheritDoc} */
public void onResume() {
// start fresh
mLogin.setText("");
mPassword.setText("");
mLogin.requestFocus();
}
/** {@inheritDoc} */
public void cleanUp() {
mContext.unbindService(this);
}
/** {@inheritDoc} */
public void onClick(View v) {
mCallback.pokeWakelock();
if (v == mOk) {
if (checkPassword()) {
// clear out forgotten password
mLockPatternUtils.setPermanentlyLocked(false);
// launch the 'choose lock pattern' activity so
// the user can pick a new one if they want to
Intent intent = new Intent();
intent.setClassName(LOCK_PATTERN_PACKAGE, LOCK_PATTERN_CLASS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
// close the keyguard
mCallback.keyguardDone(true);
} else {
mInstructions.setText(R.string.lockscreen_glogin_invalid_input);
mPassword.setText("");
}
}
if (v == mEmergencyCall) {
mCallback.takeEmergencyCallAction();
}
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
mCallback.goToLockScreen();
return true;
}
return super.dispatchKeyEvent(event);
}
private boolean checkPassword() {
final String login = mLogin.getText().toString();
final String password = mPassword.getText().toString();
try {
return mAccountsService.shouldUnlock(login, password);
} catch (RemoteException e) {
return false;
}
}
/** {@inheritDoc} */
public void onServiceConnected(ComponentName name, IBinder service) {
Log.v("AccountUnlockScreen", "debug: About to grab as interface");
mAccountsService = IAccountsService.Stub.asInterface(service);
}
/** {@inheritDoc} */
public void onServiceDisconnected(ComponentName name) {
mAccountsService = null;
}
}

View File

@@ -1,414 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import com.android.internal.R;
import com.google.android.collect.Lists;
import android.app.AlertDialog;
import android.app.StatusBarManager;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.os.LocalPowerManager;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Helper to show the global actions dialog. Each item is an {@link Action} that
* may show depending on whether the keyguard is showing, and whether the device
* is provisioned.
*/
class GlobalActions implements DialogInterface.OnDismissListener, DialogInterface.OnClickListener {
private StatusBarManager mStatusBar;
private final Context mContext;
private final LocalPowerManager mPowerManager;
private final AudioManager mAudioManager;
private ArrayList<Action> mItems;
private AlertDialog mDialog;
private ToggleAction mSilentModeToggle;
private MyAdapter mAdapter;
private boolean mKeyguardShowing = false;
private boolean mDeviceProvisioned = false;
/**
* @param context everything needs a context :)
* @param powerManager used to turn the screen off (the lock action).
*/
public GlobalActions(Context context, LocalPowerManager powerManager) {
mContext = context;
mPowerManager = powerManager;
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
// receive broadcasts
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.registerReceiver(mBroadcastReceiver, filter);
}
/**
* Show the global actions dialog (creating if necessary)
* @param keyguardShowing True if keyguard is showing
*/
public void showDialog(boolean keyguardShowing, boolean isDeviceProvisioned) {
mKeyguardShowing = keyguardShowing;
mDeviceProvisioned = isDeviceProvisioned;
if (mDialog == null) {
mStatusBar = (StatusBarManager)mContext.getSystemService(Context.STATUS_BAR_SERVICE);
mDialog = createDialog();
}
prepareDialog();
mStatusBar.disable(StatusBarManager.DISABLE_EXPAND);
mDialog.show();
}
/**
* Create the global actions dialog.
* @return A new dialog.
*/
private AlertDialog createDialog() {
mSilentModeToggle = new ToggleAction(
R.drawable.ic_lock_silent_mode,
R.drawable.ic_lock_silent_mode_off,
R.string.global_action_toggle_silent_mode,
R.string.global_action_silent_mode_on_status,
R.string.global_action_silent_mode_off_status) {
void onToggle(boolean on) {
mAudioManager.setRingerMode(on ? AudioManager.RINGER_MODE_SILENT
: AudioManager.RINGER_MODE_NORMAL);
}
public boolean showDuringKeyguard() {
return true;
}
public boolean showBeforeProvisioning() {
return false;
}
};
mItems = Lists.newArrayList(
/* Disabled pending bug 1304831 -- key or touch events wake up device before it
* can go to sleep.
// first: lock screen
new SinglePressAction(com.android.internal.R.drawable.ic_lock_lock, R.string.global_action_lock) {
public void onPress() {
mPowerManager.goToSleep(SystemClock.uptimeMillis() + 1);
}
public boolean showDuringKeyguard() {
return false;
}
public boolean showBeforeProvisioning() {
return false;
}
},
*/
// next: silent mode
mSilentModeToggle,
// last: power off
new SinglePressAction(com.android.internal.R.drawable.ic_lock_power_off, R.string.global_action_power_off) {
public void onPress() {
// shutdown by making sure radio and power are handled accordingly.
ShutdownThread.shutdownAfterDisablingRadio(mContext, true);
}
public boolean showDuringKeyguard() {
return true;
}
public boolean showBeforeProvisioning() {
return true;
}
});
mAdapter = new MyAdapter();
final AlertDialog.Builder ab = new AlertDialog.Builder(mContext);
ab.setAdapter(mAdapter, this)
.setInverseBackgroundForced(true)
.setTitle(R.string.global_actions);
final AlertDialog dialog = ab.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
dialog.setOnDismissListener(this);
return dialog;
}
private void prepareDialog() {
// TODO: May need another 'Vibrate' toggle button, but for now treat them the same
final boolean silentModeOn =
mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
mSilentModeToggle.updateState(silentModeOn);
mAdapter.notifyDataSetChanged();
if (mKeyguardShowing) {
mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
} else {
mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
}
}
/** {@inheritDoc} */
public void onDismiss(DialogInterface dialog) {
mStatusBar.disable(StatusBarManager.DISABLE_NONE);
}
/** {@inheritDoc} */
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mAdapter.getItem(which).onPress();
}
/**
* The adapter used for the list within the global actions dialog, taking
* into account whether the keyguard is showing via
* {@link GlobalActions#mKeyguardShowing} and whether the device is provisioned
* via {@link GlobalActions#mDeviceProvisioned}.
*/
private class MyAdapter extends BaseAdapter {
public int getCount() {
int count = 0;
for (int i = 0; i < mItems.size(); i++) {
final Action action = mItems.get(i);
if (mKeyguardShowing && !action.showDuringKeyguard()) {
continue;
}
if (!mDeviceProvisioned && !action.showBeforeProvisioning()) {
continue;
}
count++;
}
return count;
}
public Action getItem(int position) {
int filteredPos = 0;
for (int i = 0; i < mItems.size(); i++) {
final Action action = mItems.get(i);
if (mKeyguardShowing && !action.showDuringKeyguard()) {
continue;
}
if (!mDeviceProvisioned && !action.showBeforeProvisioning()) {
continue;
}
if (filteredPos == position) {
return action;
}
filteredPos++;
}
throw new IllegalArgumentException("position " + position + " out of "
+ "range of showable actions, filtered count = "
+ "= " + getCount() + ", keyguardshowing=" + mKeyguardShowing
+ ", provisioned=" + mDeviceProvisioned);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Action action = getItem(position);
return action.create(mContext, (LinearLayout) convertView, LayoutInflater.from(mContext));
}
}
// note: the scheme below made more sense when we were planning on having
// 8 different things in the global actions dialog. seems overkill with
// only 3 items now, but may as well keep this flexible approach so it will
// be easy should someone decide at the last minute to include something
// else, such as 'enable wifi', or 'enable bluetooth'
/**
* What each item in the global actions dialog must be able to support.
*/
private interface Action {
LinearLayout create(Context context, LinearLayout convertView, LayoutInflater inflater);
void onPress();
/**
* @return whether this action should appear in the dialog when the keygaurd
* is showing.
*/
boolean showDuringKeyguard();
/**
* @return whether this action should appear in the dialog before the
* device is provisioned.
*/
boolean showBeforeProvisioning();
}
/**
* A single press action maintains no state, just responds to a press
* and takes an action.
*/
private static abstract class SinglePressAction implements Action {
private final int mIconResId;
private final int mMessageResId;
protected SinglePressAction(int iconResId, int messageResId) {
mIconResId = iconResId;
mMessageResId = messageResId;
}
abstract public void onPress();
public LinearLayout create(Context context, LinearLayout convertView, LayoutInflater inflater) {
LinearLayout v = (LinearLayout) ((convertView != null) ?
convertView :
inflater.inflate(R.layout.global_actions_item, null));
ImageView icon = (ImageView) v.findViewById(R.id.icon);
TextView messageView = (TextView) v.findViewById(R.id.message);
v.findViewById(R.id.status).setVisibility(View.GONE);
icon.setImageDrawable(context.getResources().getDrawable(mIconResId));
messageView.setText(mMessageResId);
return v;
}
}
/**
* A toggle action knows whether it is on or off, and displays an icon
* and status message accordingly.
*/
static abstract class ToggleAction implements Action {
private boolean mOn = false;
// prefs
private final int mEnabledIconResId;
private final int mDisabledIconResid;
private final int mMessageResId;
private final int mEnabledStatusMessageResId;
private final int mDisabledStatusMessageResId;
/**
* @param enabledIconResId The icon for when this action is on.
* @param disabledIconResid The icon for when this action is off.
* @param essage The general information message, e.g 'Silent Mode'
* @param enabledStatusMessageResId The on status message, e.g 'sound disabled'
* @param disabledStatusMessageResId The off status message, e.g. 'sound enabled'
*/
public ToggleAction(int enabledIconResId,
int disabledIconResid,
int essage,
int enabledStatusMessageResId,
int disabledStatusMessageResId) {
mEnabledIconResId = enabledIconResId;
mDisabledIconResid = disabledIconResid;
mMessageResId = essage;
mEnabledStatusMessageResId = enabledStatusMessageResId;
mDisabledStatusMessageResId = disabledStatusMessageResId;
}
public LinearLayout create(Context context, LinearLayout convertView,
LayoutInflater inflater) {
LinearLayout v = (LinearLayout) ((convertView != null) ?
convertView :
inflater.inflate(R
.layout.global_actions_item, null));
ImageView icon = (ImageView) v.findViewById(R.id.icon);
TextView messageView = (TextView) v.findViewById(R.id.message);
TextView statusView = (TextView) v.findViewById(R.id.status);
messageView.setText(mMessageResId);
icon.setImageDrawable(context.getResources().getDrawable(
(mOn ? mEnabledIconResId : mDisabledIconResid)));
statusView.setText(mOn ? mEnabledStatusMessageResId : mDisabledStatusMessageResId);
statusView.setVisibility(View.VISIBLE);
return v;
}
public void onPress() {
updateState(!mOn);
onToggle(mOn);
}
abstract void onToggle(boolean on);
public void updateState(boolean on) {
mOn = on;
}
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
String reason = intent.getStringExtra(PhoneWindowManager.SYSTEM_DIALOG_REASON_KEY);
if (! PhoneWindowManager.SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS.equals(reason)) {
mHandler.sendEmptyMessage(MESSAGE_DISMISS);
}
}
}
};
private static final int MESSAGE_DISMISS = 0;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_DISMISS) {
if (mDialog != null) {
mDialog.dismiss();
}
}
}
};
}

View File

@@ -1,45 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
/**
* Common interface of each {@link android.view.View} that is a screen of
* {@link LockPatternKeyguardView}.
*/
public interface KeyguardScreen {
/**
* Return true if your view needs input, so should allow the soft
* keyboard to be displayed.
*/
boolean needsInput();
/**
* This screen is no longer in front of the user.
*/
void onPause();
/**
* This screen is going to be in front of the user.
*/
void onResume();
/**
* This view is going away; a hook to do cleanup.
*/
void cleanUp();
}

View File

@@ -1,66 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
/**
* Within a keyguard, there may be several screens that need a callback
* to the host keyguard view.
*/
public interface KeyguardScreenCallback extends KeyguardViewCallback {
/**
* Transition to the lock screen.
*/
void goToLockScreen();
/**
* Transitino to th unlock screen.
*/
void goToUnlockScreen();
/**
* @return Whether the keyguard requires some sort of PIN.
*/
boolean isSecure();
/**
* @return Whether we are in a mode where we only want to verify the
* user can get past the keyguard.
*/
boolean isVerifyUnlockOnly();
/**
* Stay on me, but recreate me (so I can use a different layout).
*/
void recreateMe();
/**
* Take action to send an emergency call.
*/
void takeEmergencyCallAction();
/**
* Report that the user had a failed attempt unlocking via the pattern.
*/
void reportFailedPatternAttempt();
/**
* Report whether we there's another way to unlock the device.
* @return true
*/
boolean doesFallbackUnlockScreenExist();
}

View File

@@ -1,552 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.ContentObserver;
import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
import static android.os.BatteryManager.BATTERY_STATUS_FULL;
import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.provider.Telephony;
import static android.provider.Telephony.Intents.EXTRA_PLMN;
import static android.provider.Telephony.Intents.EXTRA_SHOW_PLMN;
import static android.provider.Telephony.Intents.EXTRA_SHOW_SPN;
import static android.provider.Telephony.Intents.EXTRA_SPN;
import static android.provider.Telephony.Intents.SPN_STRINGS_UPDATED_ACTION;
import com.android.internal.telephony.SimCard;
import com.android.internal.telephony.TelephonyIntents;
import android.util.Log;
import com.android.internal.R;
import com.google.android.collect.Lists;
import java.util.ArrayList;
/**
* Watches for updates that may be interesting to the keyguard, and provides
* the up to date information as well as a registration for callbacks that care
* to be updated.
*
* Note: under time crunch, this has been extended to include some stuff that
* doesn't really belong here. see {@link #handleBatteryUpdate} where it shutdowns
* the device, and {@link #getFailedAttempts()}, {@link #reportFailedAttempt()}
* and {@link #clearFailedAttempts()}. Maybe we should rename this 'KeyguardContext'...
*/
public class KeyguardUpdateMonitor {
static private final String TAG = "KeyguardUpdateMonitor";
static private final boolean DEBUG = false;
private static final int LOW_BATTERY_THRESHOLD = 20;
private final Context mContext;
private SimCard.State mSimState = SimCard.State.READY;
private boolean mInPortrait;
private boolean mKeyboardOpen;
private boolean mDevicePluggedIn;
private boolean mDeviceProvisioned;
private int mBatteryLevel;
private CharSequence mTelephonyPlmn;
private CharSequence mTelephonySpn;
private int mFailedAttempts = 0;
private Handler mHandler;
private ArrayList<ConfigurationChangeCallback> mConfigurationChangeCallbacks
= Lists.newArrayList();
private ArrayList<InfoCallback> mInfoCallbacks = Lists.newArrayList();
private ArrayList<SimStateCallback> mSimStateCallbacks = Lists.newArrayList();
private ContentObserver mContentObserver;
// messages for the handler
private static final int MSG_CONFIGURATION_CHANGED = 300;
private static final int MSG_TIME_UPDATE = 301;
private static final int MSG_BATTERY_UPDATE = 302;
private static final int MSG_CARRIER_INFO_UPDATE = 303;
private static final int MSG_SIM_STATE_CHANGE = 304;
/**
* When we receive a {@link com.android.internal.telephony.TelephonyIntents#ACTION_SIM_STATE_CHANGED} broadcast, and
* then pass a result via our handler to {@link KeyguardUpdateMonitor#handleSimStateChange},
* we need a single object to pass to the handler. This class helps decode
* the intent and provide a {@link SimCard.State} result.
*/
private static class SimArgs {
public final SimCard.State simState;
private SimArgs(Intent intent) {
if (!TelephonyIntents.ACTION_SIM_STATE_CHANGED.equals(intent.getAction())) {
throw new IllegalArgumentException("only handles intent ACTION_SIM_STATE_CHANGED");
}
String stateExtra = intent.getStringExtra(SimCard.INTENT_KEY_SIM_STATE);
if (SimCard.INTENT_VALUE_SIM_ABSENT.equals(stateExtra)) {
this.simState = SimCard.State.ABSENT;
} else if (SimCard.INTENT_VALUE_SIM_READY.equals(stateExtra)) {
this.simState = SimCard.State.READY;
} else if (SimCard.INTENT_VALUE_SIM_LOCKED.equals(stateExtra)) {
final String lockedReason = intent
.getStringExtra(SimCard.INTENT_KEY_LOCKED_REASON);
if (SimCard.INTENT_VALUE_LOCKED_ON_PIN.equals(lockedReason)) {
this.simState = SimCard.State.PIN_REQUIRED;
} else if (SimCard.INTENT_VALUE_LOCKED_ON_PUK.equals(lockedReason)) {
this.simState = SimCard.State.PUK_REQUIRED;
} else {
this.simState = SimCard.State.UNKNOWN;
}
} else if (SimCard.INTENT_VALUE_LOCKED_NETWORK.equals(stateExtra)) {
this.simState = SimCard.State.NETWORK_LOCKED;
} else {
this.simState = SimCard.State.UNKNOWN;
}
}
public String toString() {
return simState.toString();
}
}
public KeyguardUpdateMonitor(Context context) {
mContext = context;
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_CONFIGURATION_CHANGED:
handleConfigurationChange();
break;
case MSG_TIME_UPDATE:
handleTimeUpdate();
break;
case MSG_BATTERY_UPDATE:
handleBatteryUpdate(msg.arg1, msg.arg2);
break;
case MSG_CARRIER_INFO_UPDATE:
handleCarrierInfoUpdate();
break;
case MSG_SIM_STATE_CHANGE:
handleSimStateChange((SimArgs) msg.obj);
break;
}
}
};
mDeviceProvisioned = Settings.Secure.getInt(
mContext.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
// Since device can't be un-provisioned, we only need to register a content observer
// to update mDeviceProvisioned when we are...
if (!mDeviceProvisioned) {
mContentObserver = new ContentObserver(mHandler) {
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
mDeviceProvisioned = Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
if (mDeviceProvisioned && mContentObserver != null) {
// We don't need the observer anymore...
mContext.getContentResolver().unregisterContentObserver(mContentObserver);
mContentObserver = null;
}
if (DEBUG) Log.d(TAG, "DEVICE_PROVISIONED state = " + mDeviceProvisioned);
}
};
mContext.getContentResolver().registerContentObserver(
Settings.Secure.getUriFor(Settings.Secure.DEVICE_PROVISIONED),
false, mContentObserver);
// prevent a race condition between where we check the flag and where we register the
// observer by grabbing the value once again...
mDeviceProvisioned = Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
}
mInPortrait = queryInPortrait();
mKeyboardOpen = queryKeyboardOpen();
// take a guess to start
mSimState = SimCard.State.READY;
mDevicePluggedIn = true;
mBatteryLevel = 100;
mTelephonyPlmn = getDefaultPlmn();
// setup receiver
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
filter.addAction(SPN_STRINGS_UPDATED_ACTION);
context.registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (DEBUG) Log.d(TAG, "received broadcast " + action);
if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
mHandler.sendMessage(mHandler.obtainMessage(MSG_CONFIGURATION_CHANGED));
} else if (Intent.ACTION_TIME_TICK.equals(action)
|| Intent.ACTION_TIME_CHANGED.equals(action)
|| Intent.ACTION_TIMEZONE_CHANGED.equals(action)) {
mHandler.sendMessage(mHandler.obtainMessage(MSG_TIME_UPDATE));
} else if (SPN_STRINGS_UPDATED_ACTION.equals(action)) {
mTelephonyPlmn = getTelephonyPlmnFrom(intent);
mTelephonySpn = getTelephonySpnFrom(intent);
mHandler.sendMessage(mHandler.obtainMessage(MSG_CARRIER_INFO_UPDATE));
} else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
final int pluggedInStatus = intent
.getIntExtra("status", BATTERY_STATUS_UNKNOWN);
int batteryLevel = intent.getIntExtra("level", 0);
final Message msg = mHandler.obtainMessage(
MSG_BATTERY_UPDATE,
pluggedInStatus,
batteryLevel);
mHandler.sendMessage(msg);
} else if (TelephonyIntents.ACTION_SIM_STATE_CHANGED.equals(action)){
mHandler.sendMessage(mHandler.obtainMessage(
MSG_SIM_STATE_CHANGE,
new SimArgs(intent)));
}
}
}, filter);
}
/**
* Handle {@link #MSG_CONFIGURATION_CHANGED}
*/
private void handleConfigurationChange() {
if (DEBUG) Log.d(TAG, "handleConfigurationChange");
final boolean inPortrait = queryInPortrait();
if (mInPortrait != inPortrait) {
mInPortrait = inPortrait;
for (int i = 0; i < mConfigurationChangeCallbacks.size(); i++) {
mConfigurationChangeCallbacks.get(i).onOrientationChange(inPortrait);
}
}
final boolean keyboardOpen = queryKeyboardOpen();
if (mKeyboardOpen != keyboardOpen) {
mKeyboardOpen = keyboardOpen;
for (int i = 0; i < mConfigurationChangeCallbacks.size(); i++) {
mConfigurationChangeCallbacks.get(i).onKeyboardChange(keyboardOpen);
}
}
}
/**
* Handle {@link #MSG_TIME_UPDATE}
*/
private void handleTimeUpdate() {
if (DEBUG) Log.d(TAG, "handleTimeUpdate");
for (int i = 0; i < mInfoCallbacks.size(); i++) {
mInfoCallbacks.get(i).onTimeChanged();
}
}
/**
* Handle {@link #MSG_BATTERY_UPDATE}
*/
private void handleBatteryUpdate(int pluggedInStatus, int batteryLevel) {
if (DEBUG) Log.d(TAG, "handleBatteryUpdate");
final boolean pluggedIn = isPluggedIn(pluggedInStatus);
if (isBatteryUpdateInteresting(pluggedIn, batteryLevel)) {
mBatteryLevel = batteryLevel;
mDevicePluggedIn = pluggedIn;
for (int i = 0; i < mInfoCallbacks.size(); i++) {
mInfoCallbacks.get(i).onRefreshBatteryInfo(
shouldShowBatteryInfo(), pluggedIn, batteryLevel);
}
}
// shut down gracefully if our battery is critically low and we are not powered
if (batteryLevel == 0 &&
pluggedInStatus != BATTERY_STATUS_CHARGING &&
pluggedInStatus != BATTERY_STATUS_UNKNOWN) {
ShutdownThread.shutdownAfterDisablingRadio(mContext, false);
}
}
/**
* Handle {@link #MSG_CARRIER_INFO_UPDATE}
*/
private void handleCarrierInfoUpdate() {
if (DEBUG) Log.d(TAG, "handleCarrierInfoUpdate: plmn = " + mTelephonyPlmn
+ ", spn = " + mTelephonySpn);
for (int i = 0; i < mInfoCallbacks.size(); i++) {
mInfoCallbacks.get(i).onRefreshCarrierInfo(mTelephonyPlmn, mTelephonySpn);
}
}
/**
* Handle {@link #MSG_SIM_STATE_CHANGE}
*/
private void handleSimStateChange(SimArgs simArgs) {
final SimCard.State state = simArgs.simState;
if (DEBUG) {
Log.d(TAG, "handleSimStateChange: intentValue = " + simArgs + " "
+ "state resolved to " + state.toString());
}
if (state != SimCard.State.UNKNOWN && state != mSimState) {
mSimState = state;
for (int i = 0; i < mSimStateCallbacks.size(); i++) {
mSimStateCallbacks.get(i).onSimStateChanged(state);
}
}
}
/**
* @param status One of the statuses of {@link android.os.BatteryManager}
* @return Whether the status maps to a status for being plugged in.
*/
private boolean isPluggedIn(int status) {
return status == BATTERY_STATUS_CHARGING || status == BATTERY_STATUS_FULL;
}
private boolean isBatteryUpdateInteresting(boolean pluggedIn, int batteryLevel) {
// change in plug is always interesting
if (mDevicePluggedIn != pluggedIn) {
return true;
}
// change in battery level while plugged in
if (pluggedIn && mBatteryLevel != batteryLevel) {
return true;
}
if (!pluggedIn) {
// not plugged in and going below threshold
if (batteryLevel < LOW_BATTERY_THRESHOLD
&& mBatteryLevel >= LOW_BATTERY_THRESHOLD) {
return true;
}
// not plugged in and going above threshold (sounds impossible, but, meh...)
if (mBatteryLevel < LOW_BATTERY_THRESHOLD
&& batteryLevel >= LOW_BATTERY_THRESHOLD) {
return true;
}
}
return false;
}
/**
* What is the current orientation?
*/
boolean queryInPortrait() {
final Configuration configuration = mContext.getResources().getConfiguration();
return configuration.orientation == Configuration.ORIENTATION_PORTRAIT;
}
/**
* Is the (hard) keyboard currently open?
*/
boolean queryKeyboardOpen() {
final Configuration configuration = mContext.getResources().getConfiguration();
return configuration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO;
}
/**
* @param intent The intent with action {@link Telephony.Intents#SPN_STRINGS_UPDATED_ACTION}
* @return The string to use for the plmn, or null if it should not be shown.
*/
private CharSequence getTelephonyPlmnFrom(Intent intent) {
if (intent.getBooleanExtra(EXTRA_SHOW_PLMN, false)) {
final String plmn = intent.getStringExtra(EXTRA_PLMN);
if (plmn != null) {
return plmn;
} else {
return getDefaultPlmn();
}
}
return null;
}
/**
* @return The default plmn (no service)
*/
private CharSequence getDefaultPlmn() {
return mContext.getResources().getText(
R.string.lockscreen_carrier_default);
}
/**
* @param intent The intent with action {@link Telephony.Intents#SPN_STRINGS_UPDATED_ACTION}
* @return The string to use for the plmn, or null if it should not be shown.
*/
private CharSequence getTelephonySpnFrom(Intent intent) {
if (intent.getBooleanExtra(EXTRA_SHOW_SPN, false)) {
final String spn = intent.getStringExtra(EXTRA_SPN);
if (spn != null) {
return spn;
}
}
return null;
}
/**
* Remove the given observer from being registered from any of the kinds
* of callbacks.
* @param observer The observer to remove (an instance of {@link ConfigurationChangeCallback},
* {@link InfoCallback} or {@link SimStateCallback}
*/
public void removeCallback(Object observer) {
mConfigurationChangeCallbacks.remove(observer);
mInfoCallbacks.remove(observer);
mSimStateCallbacks.remove(observer);
}
/**
* Callback for configuration changes.
*/
interface ConfigurationChangeCallback {
void onOrientationChange(boolean inPortrait);
void onKeyboardChange(boolean isKeyboardOpen);
}
/**
* Callback for general information releveant to lock screen.
*/
interface InfoCallback {
void onRefreshBatteryInfo(boolean showBatteryInfo, boolean pluggedIn, int batteryLevel);
void onTimeChanged();
/**
* @param plmn The operator name of the registered network. May be null if it shouldn't
* be displayed.
* @param spn The service provider name. May be null if it shouldn't be displayed.
*/
void onRefreshCarrierInfo(CharSequence plmn, CharSequence spn);
}
/**
* Callback to notify of sim state change.
*/
interface SimStateCallback {
void onSimStateChanged(SimCard.State simState);
}
/**
* Register to receive notifications about configuration changes.
* @param callback The callback.
*/
public void registerConfigurationChangeCallback(ConfigurationChangeCallback callback) {
mConfigurationChangeCallbacks.add(callback);
}
/**
* Register to receive notifications about general keyguard information
* (see {@link InfoCallback}.
* @param callback The callback.
*/
public void registerInfoCallback(InfoCallback callback) {
mInfoCallbacks.add(callback);
}
/**
* Register to be notified of sim state changes.
* @param callback The callback.
*/
public void registerSimStateCallback(SimStateCallback callback) {
mSimStateCallbacks.add(callback);
}
public SimCard.State getSimState() {
return mSimState;
}
/**
* Report that the user succesfully entered the sim pin so we
* have the information earlier than waiting for the intent
* broadcast from the telephony code.
*/
public void reportSimPinUnlocked() {
mSimState = SimCard.State.READY;
}
public boolean isInPortrait() {
return mInPortrait;
}
public boolean isKeyboardOpen() {
return mKeyboardOpen;
}
public boolean isDevicePluggedIn() {
return mDevicePluggedIn;
}
public int getBatteryLevel() {
return mBatteryLevel;
}
public boolean shouldShowBatteryInfo() {
return mDevicePluggedIn || mBatteryLevel < LOW_BATTERY_THRESHOLD;
}
public CharSequence getTelephonyPlmn() {
return mTelephonyPlmn;
}
public CharSequence getTelephonySpn() {
return mTelephonySpn;
}
/**
* @return Whether the device is provisioned (whether they have gone through
* the setup wizard)
*/
public boolean isDeviceProvisioned() {
return mDeviceProvisioned;
}
public int getFailedAttempts() {
return mFailedAttempts;
}
public void clearFailedAttempts() {
mFailedAttempts = 0;
}
public void reportFailedAttempt() {
mFailedAttempts++;
}
}

View File

@@ -1,188 +0,0 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
/**
* Base class for keyguard views. {@link #reset} is where you should
* reset the state of your view. Use the {@link KeyguardViewCallback} via
* {@link #getCallback()} to send information back (such as poking the wake lock,
* or finishing the keyguard).
*
* Handles intercepting of media keys that still work when the keyguard is
* showing.
*/
public abstract class KeyguardViewBase extends FrameLayout {
private KeyguardViewCallback mCallback;
private AudioManager mAudioManager;
public KeyguardViewBase(Context context) {
super(context);
}
// used to inject callback
void setCallback(KeyguardViewCallback callback) {
mCallback = callback;
}
public KeyguardViewCallback getCallback() {
return mCallback;
}
/**
* Called when you need to reset the state of your view.
*/
abstract public void reset();
/**
* Called when the screen turned off.
*/
abstract public void onScreenTurnedOff();
/**
* Called when the screen turned on.
*/
abstract public void onScreenTurnedOn();
/**
* Called when a key has woken the device to give us a chance to adjust our
* state according the the key. We are responsible for waking the device
* (by poking the wake lock) once we are ready.
*
* The 'Tq' suffix is per the documentation in {@link android.view.WindowManagerPolicy}.
* Be sure not to take any action that takes a long time; any significant
* action should be posted to a handler.
*
* @param keyCode The wake key, which may be relevant for configuring the
* keyguard.
*/
abstract public void wakeWhenReadyTq(int keyCode);
/**
* Verify that the user can get past the keyguard securely. This is called,
* for example, when the phone disables the keyguard but then wants to launch
* something else that requires secure access.
*
* The result will be propogated back via {@link KeyguardViewCallback#keyguardDone(boolean)}
*/
abstract public void verifyUnlock();
/**
* Called before this view is being removed.
*/
abstract public void cleanUp();
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (shouldEventKeepScreenOnWhileKeyguardShowing(event)) {
mCallback.pokeWakelock();
}
if (interceptMediaKey(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
private boolean shouldEventKeepScreenOnWhileKeyguardShowing(KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_UP:
return false;
default:
return true;
}
}
/**
* Allows the media keys to work when the keygaurd is showing.
* The media keys should be of no interest to the actualy keygaurd view(s),
* so intercepting them here should not be of any harm.
* @param event The key event
* @return whether the event was consumed as a media key.
*/
private boolean interceptMediaKey(KeyEvent event) {
final int keyCode = event.getKeyCode();
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_PLAYPAUSE:
case KeyEvent.KEYCODE_STOP:
case KeyEvent.KEYCODE_NEXTSONG:
case KeyEvent.KEYCODE_PREVIOUSSONG:
case KeyEvent.KEYCODE_REWIND:
case KeyEvent.KEYCODE_FORWARD: {
Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
intent.putExtra(Intent.EXTRA_KEY_EVENT, event);
getContext().sendOrderedBroadcast(intent, null);
return true;
}
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN: {
synchronized (this) {
if (mAudioManager == null) {
mAudioManager = (AudioManager) getContext().getSystemService(
Context.AUDIO_SERVICE);
}
}
// Volume buttons should only function for music.
if (mAudioManager.isMusicActive()) {
mAudioManager.adjustStreamVolume(
AudioManager.STREAM_MUSIC,
keyCode == KeyEvent.KEYCODE_VOLUME_UP
? AudioManager.ADJUST_RAISE
: AudioManager.ADJUST_LOWER,
0);
}
// Don't execute default volume behavior
return true;
}
}
} else if (event.getAction() == KeyEvent.ACTION_UP) {
switch (keyCode) {
case KeyEvent.KEYCODE_MUTE:
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_PLAYPAUSE:
case KeyEvent.KEYCODE_STOP:
case KeyEvent.KEYCODE_NEXTSONG:
case KeyEvent.KEYCODE_PREVIOUSSONG:
case KeyEvent.KEYCODE_REWIND:
case KeyEvent.KEYCODE_FORWARD: {
Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
intent.putExtra(Intent.EXTRA_KEY_EVENT, event);
getContext().sendOrderedBroadcast(intent, null);
return true;
}
}
}
return false;
}
}

View File

@@ -1,49 +0,0 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
/**
* The callback used by the keyguard view to tell the {@link KeyguardViewMediator}
* various things.
*/
public interface KeyguardViewCallback {
/**
* Request the wakelock to be poked for the default amount of time.
*/
void pokeWakelock();
/**
* Request the wakelock to be poked for a specific amount of time.
* @param millis The amount of time in millis.
*/
void pokeWakelock(int millis);
/**
* Report that the keyguard is done.
* @param authenticated Whether the user securely got past the keyguard.
* the only reason for this to be false is if the keyguard was instructed
* to appear temporarily to verify the user is supposed to get past the
* keyguard, and the user fails to do so.
*/
void keyguardDone(boolean authenticated);
/**
* Report that the keyguard is done drawing.
*/
void keyguardDoneDrawing();
}

View File

@@ -1,226 +0,0 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import com.android.internal.R;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.graphics.Canvas;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewManager;
import android.view.WindowManager;
import android.widget.FrameLayout;
/**
* Manages creating, showing, hiding and resetting the keyguard. Calls back
* via {@link com.android.internal.policy.impl.KeyguardViewCallback} to poke
* the wake lock and report that the keyguard is done, which is in turn,
* reported to this class by the current {@link KeyguardViewBase}.
*/
public class KeyguardViewManager implements KeyguardWindowController {
private final static boolean DEBUG = false;
private static String TAG = "KeyguardViewManager";
private final Context mContext;
private final ViewManager mViewManager;
private final KeyguardViewCallback mCallback;
private final KeyguardViewProperties mKeyguardViewProperties;
private final KeyguardUpdateMonitor mUpdateMonitor;
private WindowManager.LayoutParams mWindowLayoutParams;
private boolean mNeedsInput = false;
private FrameLayout mKeyguardHost;
private KeyguardViewBase mKeyguardView;
private boolean mScreenOn = false;
/**
* @param context Used to create views.
* @param viewManager Keyguard will be attached to this.
* @param callback Used to notify of changes.
*/
public KeyguardViewManager(Context context, ViewManager viewManager,
KeyguardViewCallback callback, KeyguardViewProperties keyguardViewProperties, KeyguardUpdateMonitor updateMonitor) {
mContext = context;
mViewManager = viewManager;
mCallback = callback;
mKeyguardViewProperties = keyguardViewProperties;
mUpdateMonitor = updateMonitor;
}
/**
* Helper class to host the keyguard view.
*/
private static class KeyguardViewHost extends FrameLayout {
private final KeyguardViewCallback mCallback;
private KeyguardViewHost(Context context, KeyguardViewCallback callback) {
super(context);
mCallback = callback;
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
mCallback.keyguardDoneDrawing();
}
}
/**
* Show the keyguard. Will handle creating and attaching to the view manager
* lazily.
*/
public synchronized void show() {
if (DEBUG) Log.d(TAG, "show()");
if (mKeyguardHost == null) {
if (DEBUG) Log.d(TAG, "keyguard host is null, creating it...");
mKeyguardHost = new KeyguardViewHost(mContext, mCallback);
final int stretch = ViewGroup.LayoutParams.FILL_PARENT;
int flags = WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN
/*| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR*/ ;
if (!mNeedsInput) {
flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
}
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
stretch, stretch, WindowManager.LayoutParams.TYPE_KEYGUARD,
flags, PixelFormat.OPAQUE);
lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
lp.windowAnimations = com.android.internal.R.style.Animation_LockScreen;
lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
lp.setTitle("Keyguard");
mWindowLayoutParams = lp;
mViewManager.addView(mKeyguardHost, lp);
}
if (mKeyguardView == null) {
if (DEBUG) Log.d(TAG, "keyguard view is null, creating it...");
mKeyguardView = mKeyguardViewProperties.createKeyguardView(mContext, mUpdateMonitor, this);
mKeyguardView.setId(R.id.lock_screen);
mKeyguardView.setCallback(mCallback);
final ViewGroup.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
mKeyguardHost.addView(mKeyguardView, lp);
if (mScreenOn) {
mKeyguardView.onScreenTurnedOn();
}
}
mKeyguardHost.setVisibility(View.VISIBLE);
mKeyguardView.requestFocus();
}
public void setNeedsInput(boolean needsInput) {
mNeedsInput = needsInput;
if (mWindowLayoutParams != null) {
if (needsInput) {
mWindowLayoutParams.flags &=
~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
} else {
mWindowLayoutParams.flags |=
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
}
mViewManager.updateViewLayout(mKeyguardHost, mWindowLayoutParams);
}
}
/**
* Reset the state of the view.
*/
public synchronized void reset() {
if (DEBUG) Log.d(TAG, "reset()");
if (mKeyguardView != null) {
mKeyguardView.reset();
}
}
public synchronized void onScreenTurnedOff() {
if (DEBUG) Log.d(TAG, "onScreenTurnedOff()");
mScreenOn = false;
if (mKeyguardView != null) {
mKeyguardView.onScreenTurnedOff();
}
}
public synchronized void onScreenTurnedOn() {
if (DEBUG) Log.d(TAG, "onScreenTurnedOn()");
mScreenOn = true;
if (mKeyguardView != null) {
mKeyguardView.onScreenTurnedOn();
}
}
public synchronized void verifyUnlock() {
if (DEBUG) Log.d(TAG, "verifyUnlock()");
show();
mKeyguardView.verifyUnlock();
}
/**
* A key has woken the device. We use this to potentially adjust the state
* of the lock screen based on the key.
*
* The 'Tq' suffix is per the documentation in {@link android.view.WindowManagerPolicy}.
* Be sure not to take any action that takes a long time; any significant
* action should be posted to a handler.
*
* @param keyCode The wake key.
*/
public void wakeWhenReadyTq(int keyCode) {
if (DEBUG) Log.d(TAG, "wakeWhenReady(" + keyCode + ")");
if (mKeyguardView != null) {
mKeyguardView.wakeWhenReadyTq(keyCode);
}
}
/**
* Hides the keyguard view
*/
public synchronized void hide() {
if (DEBUG) Log.d(TAG, "hide()");
if (mKeyguardHost != null) {
mKeyguardHost.setVisibility(View.GONE);
if (mKeyguardView != null) {
mKeyguardHost.removeView(mKeyguardView);
mKeyguardView.cleanUp();
mKeyguardView = null;
}
}
}
/**
* @return Whether the keyguard is showing
*/
public synchronized boolean isShowing() {
return (mKeyguardHost != null && mKeyguardHost.getVisibility() == View.VISIBLE);
}
}

View File

@@ -1,915 +0,0 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.StatusBarManager;
import static android.app.StatusBarManager.DISABLE_NONE;
import static android.app.StatusBarManager.DISABLE_EXPAND;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.LocalPowerManager;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Config;
import android.util.Log;
import android.util.EventLog;
import android.view.KeyEvent;
import android.view.WindowManagerImpl;
import android.view.WindowManagerPolicy;
import com.android.internal.telephony.SimCard;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.widget.LockPatternUtils;
/**
* Mediates requests related to the keyguard. This includes queries about the
* state of the keyguard, power management events that effect whether the keyguard
* should be shown or reset, callbacks to the phone window manager to notify
* it of when the keyguard is showing, and events from the keyguard view itself
* stating that the keyguard was succesfully unlocked.
*
* Note that the keyguard view is shown when the screen is off (as appropriate)
* so that once the screen comes on, it will be ready immediately.
*
* Example queries about the keyguard:
* - is {movement, key} one that should wake the keygaurd?
* - is the keyguard showing?
* - are input events restricted due to the state of the keyguard?
*
* Callbacks to the phone window manager:
* - the keyguard is showing
*
* Example external events that translate to keyguard view changes:
* - screen turned off -> reset the keyguard, and show it so it will be ready
* next time the screen turns on
* - keyboard is slid open -> if the keyguard is not secure, hide it
*
* Events from the keyguard view:
* - user succesfully unlocked keyguard -> hide keyguard view, and no longer
* restrict input events.
*
* Note: in addition to normal power managment events that effect the state of
* whether the keyguard should be showing, external apps and services may request
* that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}. When
* false, this will override all other conditions for turning on the keyguard.
*
* Threading and synchronization:
* This class is created by the initialization routine of the {@link WindowManagerPolicy},
* and runs on its thread. The keyguard UI is created from that thread in the
* constructor of this class. The apis may be called from other threads, including the
* {@link com.android.server.KeyInputQueue}'s and {@link android.view.WindowManager}'s.
* Therefore, methods on this class are synchronized, and any action that is pointed
* directly to the keyguard UI is posted to a {@link Handler} to ensure it is taken on the UI
* thread of the keyguard.
*/
public class KeyguardViewMediator implements KeyguardViewCallback,
KeyguardUpdateMonitor.ConfigurationChangeCallback, KeyguardUpdateMonitor.SimStateCallback {
private final static boolean DEBUG = false && Config.LOGD;
private final static boolean DBG_WAKE = DEBUG || true;
private final static String TAG = "KeyguardViewMediator";
private static final String DELAYED_KEYGUARD_ACTION = "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD";
// used for handler messages
private static final int TIMEOUT = 1;
private static final int SHOW = 2;
private static final int HIDE = 3;
private static final int RESET = 4;
private static final int VERIFY_UNLOCK = 5;
private static final int NOTIFY_SCREEN_OFF = 6;
private static final int NOTIFY_SCREEN_ON = 7;
private static final int WAKE_WHEN_READY = 8;
private static final int KEYGUARD_DONE = 9;
private static final int KEYGUARD_DONE_DRAWING = 10;
/**
* The default amount of time we stay awake (used for all key input)
*/
protected static final int AWAKE_INTERVAL_DEFAULT_MS = 5000;
/**
* The default amount of time we stay awake (used for all key input) when
* the keyboard is open
*/
protected static final int AWAKE_INTERVAL_DEFAULT_KEYBOARD_OPEN_MS = 10000;
/**
* How long to wait after the screen turns off due to timeout before
* turning on the keyguard (i.e, the user has this much time to turn
* the screen back on without having to face the keyguard).
*/
private static final int KEYGUARD_DELAY_MS = 0;
/**
* How long we'll wait for the {@link KeyguardViewCallback#keyguardDoneDrawing()}
* callback before unblocking a call to {@link #setKeyguardEnabled(boolean)}
* that is reenabling the keyguard.
*/
private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000;
private Context mContext;
private AlarmManager mAlarmManager;
private boolean mSystemReady;
/** Low level access to the power manager for enableUserActivity. Having this
* requires that we run in the system process. */
LocalPowerManager mRealPowerManager;
/** High level access to the power manager for WakeLocks */
private PowerManager mPM;
/**
* Used to keep the device awake while the keyguard is showing, i.e for
* calls to {@link #pokeWakelock()}
*/
private PowerManager.WakeLock mWakeLock;
/**
* Does not turn on screen, held while a call to {@link KeyguardViewManager#wakeWhenReadyTq(int)}
* is called to make sure the device doesn't sleep before it has a chance to poke
* the wake lock.
* @see #wakeWhenReadyLocked(int)
*/
private PowerManager.WakeLock mWakeAndHandOff;
/**
* Used to disable / reenable status bar expansion.
*/
private StatusBarManager mStatusBarManager;
private KeyguardViewManager mKeyguardViewManager;
// these are protected by synchronized (this)
/**
* External apps (like the phone app) can tell us to disable the keygaurd.
*/
private boolean mExternallyEnabled = true;
/**
* Remember if an external call to {@link #setKeyguardEnabled} with value
* false caused us to hide the keyguard, so that we need to reshow it once
* the keygaurd is reenabled with another call with value true.
*/
private boolean mNeedToReshowWhenReenabled = false;
// cached value of whether we are showing (need to know this to quickly
// answer whether the input should be restricted)
private boolean mShowing = false;
/**
* Helps remember whether the screen has turned on since the last time
* it turned off due to timeout. see {@link #onScreenTurnedOff(int)}
*/
private int mDelayedShowingSequence;
private int mWakelockSequence;
private PhoneWindowManager mCallback;
/**
* If the user has disabled the keyguard, then requests to exit, this is
* how we'll ultimately let them know whether it was successful. We use this
* var being non-null as an indicator that there is an in progress request.
*/
private WindowManagerPolicy.OnKeyguardExitResult mExitSecureCallback;
// the properties of the keyguard
private KeyguardViewProperties mKeyguardViewProperties;
private KeyguardUpdateMonitor mUpdateMonitor;
private boolean mKeyboardOpen = false;
/**
* {@link #setKeyguardEnabled} waits on this condition when it reenables
* the keyguard.
*/
private boolean mWaitingUntilKeyguardVisible = false;
public KeyguardViewMediator(Context context, PhoneWindowManager callback,
LocalPowerManager powerManager) {
mContext = context;
mRealPowerManager = powerManager;
mPM = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = mPM.newWakeLock(
PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
"keyguard");
mWakeLock.setReferenceCounted(false);
mWakeAndHandOff = mPM.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK,
"keyguardWakeAndHandOff");
mWakeAndHandOff.setReferenceCounted(false);
IntentFilter filter = new IntentFilter();
filter.addAction(DELAYED_KEYGUARD_ACTION);
filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
context.registerReceiver(mBroadCastReceiver, filter);
mAlarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
mCallback = callback;
mUpdateMonitor = new KeyguardUpdateMonitor(context);
mUpdateMonitor.registerConfigurationChangeCallback(this);
mUpdateMonitor.registerSimStateCallback(this);
mKeyguardViewProperties =
new LockPatternKeyguardViewProperties(
new LockPatternUtils(mContext.getContentResolver()),
mUpdateMonitor);
mKeyguardViewManager = new KeyguardViewManager(
context, WindowManagerImpl.getDefault(), this,
mKeyguardViewProperties, mUpdateMonitor);
}
/**
* Let us know that the system is ready after startup.
*/
public void onSystemReady() {
synchronized (this) {
if (DEBUG) Log.d(TAG, "onSystemReady");
mSystemReady = true;
doKeyguard();
}
}
/**
* Called to let us know the screen was turned off.
* @param why either {@link WindowManagerPolicy#OFF_BECAUSE_OF_USER} or
* {@link WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT}.
*/
public void onScreenTurnedOff(int why) {
synchronized (this) {
if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");
if (mExitSecureCallback != null) {
if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
mExitSecureCallback.onKeyguardExitResult(false);
mExitSecureCallback = null;
if (!mExternallyEnabled) {
hideLocked();
}
} else if (mShowing) {
notifyScreenOffLocked();
resetStateLocked();
} else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT) {
// if the screen turned off because of timeout, set an alarm
// to enable it a little bit later (i.e, give the user a chance
// to turn the screen back on within a certain window without
// having to unlock the screen)
long when = SystemClock.elapsedRealtime() + KEYGUARD_DELAY_MS;
Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
intent.putExtra("seq", mDelayedShowingSequence);
PendingIntent sender = PendingIntent.getBroadcast(mContext,
0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when,
sender);
if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = " + mDelayedShowingSequence);
} else {
doKeyguard();
}
}
}
/**
* Let's us know the screen was turned on.
*/
public void onScreenTurnedOn() {
synchronized (this) {
mDelayedShowingSequence++;
if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
notifyScreenOnLocked();
}
}
/**
* Same semantics as {@link WindowManagerPolicy#enableKeyguard}; provide
* a way for external stuff to override normal keyguard behavior. For instance
* the phone app disables the keyguard when it receives incoming calls.
*/
public void setKeyguardEnabled(boolean enabled) {
synchronized (this) {
if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
mExternallyEnabled = enabled;
if (!enabled && mShowing) {
if (mExitSecureCallback != null) {
if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
// we're in the process of handling a request to verify the user
// can get past the keyguard. ignore extraneous requests to disable / reenable
return;
}
// hiding keyguard that is showing, remember to reshow later
if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
+ "disabling status bar expansion");
mNeedToReshowWhenReenabled = true;
setStatusBarExpandable(false);
hideLocked();
} else if (enabled && mNeedToReshowWhenReenabled) {
// reenabled after previously hidden, reshow
if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
+ "status bar expansion");
mNeedToReshowWhenReenabled = false;
setStatusBarExpandable(true);
if (mExitSecureCallback != null) {
if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
mExitSecureCallback.onKeyguardExitResult(false);
mExitSecureCallback = null;
resetStateLocked();
} else {
showLocked();
// block until we know the keygaurd is done drawing (and post a message
// to unblock us after a timeout so we don't risk blocking too long
// and causing an ANR).
mWaitingUntilKeyguardVisible = true;
mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
while (mWaitingUntilKeyguardVisible) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
}
}
}
}
/**
* @see android.app.KeyguardManager#exitKeyguardSecurely
*/
public void verifyUnlock(WindowManagerPolicy.OnKeyguardExitResult callback) {
synchronized (this) {
if (DEBUG) Log.d(TAG, "verifyUnlock");
if (!mUpdateMonitor.isDeviceProvisioned()) {
// don't allow this api when the device isn't provisioned
if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
callback.onKeyguardExitResult(false);
} else if (mExternallyEnabled) {
// this only applies when the user has externally disabled the
// keyguard. this is unexpected and means the user is not
// using the api properly.
Log.w(TAG, "verifyUnlock called when not externally disabled");
callback.onKeyguardExitResult(false);
} else if (mExitSecureCallback != null) {
// already in progress with someone else
callback.onKeyguardExitResult(false);
} else {
mExitSecureCallback = callback;
verifyUnlockLocked();
}
}
}
private void setStatusBarExpandable(boolean isExpandable) {
if (mStatusBarManager == null) {
mStatusBarManager =
(StatusBarManager) mContext.getSystemService(Context.STATUS_BAR_SERVICE);
}
mStatusBarManager.disable(isExpandable ? DISABLE_NONE : DISABLE_EXPAND);
}
/**
* Is the keyguard currently showing?
*/
public boolean isShowing() {
return mShowing;
}
/**
* Given the state of the keyguard, is the input restricted?
* Input is restricted when the keyguard is showing, or when the keyguard
* was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
*/
public boolean isInputRestricted() {
return mShowing || mNeedToReshowWhenReenabled || !mUpdateMonitor.isDeviceProvisioned();
}
/**
* Enable the keyguard if the settings are appropriate.
*/
private void doKeyguard() {
synchronized (this) {
// if another app is disabling us, don't show
if (!mExternallyEnabled) {
if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
return;
}
// if the keyguard is already showing, don't bother
if (mKeyguardViewManager.isShowing()) {
if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
return;
}
// if the setup wizard hasn't run yet, don't show
final boolean provisioned = mUpdateMonitor.isDeviceProvisioned();
final SimCard.State state = mUpdateMonitor.getSimState();
final boolean lockedOrMissing = state.isPinLocked() || (state == SimCard.State.ABSENT);
if (!lockedOrMissing && !provisioned) {
if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
+ " and the sim is not locked or missing");
return;
}
if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
showLocked();
}
}
/**
* Send message to keyguard telling it to reset its state.
* @see #handleReset()
*/
private void resetStateLocked() {
if (DEBUG) Log.d(TAG, "resetStateLocked");
Message msg = mHandler.obtainMessage(RESET);
mHandler.sendMessage(msg);
}
/**
* Send message to keyguard telling it to verify unlock
* @see #handleVerifyUnlock()
*/
private void verifyUnlockLocked() {
if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
mHandler.sendEmptyMessage(VERIFY_UNLOCK);
}
/**
* Send a message to keyguard telling it the screen just turned on.
* @see #onScreenTurnedOff(int)
* @see #handleNotifyScreenOff
*/
private void notifyScreenOffLocked() {
if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
}
/**
* Send a message to keyguard telling it the screen just turned on.
* @see #onScreenTurnedOn()
* @see #handleNotifyScreenOn
*/
private void notifyScreenOnLocked() {
if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
mHandler.sendEmptyMessage(NOTIFY_SCREEN_ON);
}
/**
* Send message to keyguard telling it about a wake key so it can adjust
* its state accordingly and then poke the wake lock when it is ready.
* @param keyCode The wake key.
* @see #handleWakeWhenReady
* @see #onWakeKeyWhenKeyguardShowingTq(int)
*/
private void wakeWhenReadyLocked(int keyCode) {
if (DBG_WAKE) Log.d(TAG, "wakeWhenReadyLocked(" + keyCode + ")");
/**
* acquire the handoff lock that will keep the cpu running. this will
* be released once the keyguard has set itself up and poked the other wakelock
* in {@link #handleWakeWhenReady(int)}
*/
mWakeAndHandOff.acquire();
Message msg = mHandler.obtainMessage(WAKE_WHEN_READY, keyCode, 0);
mHandler.sendMessage(msg);
}
/**
* Send message to keyguard telling it to show itself
* @see #handleShow()
*/
private void showLocked() {
if (DEBUG) Log.d(TAG, "showLocked");
Message msg = mHandler.obtainMessage(SHOW);
mHandler.sendMessage(msg);
}
/**
* Send message to keyguard telling it to hide itself
* @see #handleHide()
*/
private void hideLocked() {
if (DEBUG) Log.d(TAG, "hideLocked");
Message msg = mHandler.obtainMessage(HIDE);
mHandler.sendMessage(msg);
}
/**
* {@link KeyguardUpdateMonitor} callbacks.
*/
/** {@inheritDoc} */
public void onOrientationChange(boolean inPortrait) {
}
/** {@inheritDoc} */
public void onKeyboardChange(boolean isKeyboardOpen) {
mKeyboardOpen = isKeyboardOpen;
if (mKeyboardOpen && !mKeyguardViewProperties.isSecure()
&& mKeyguardViewManager.isShowing()) {
if (DEBUG) Log.d(TAG, "bypassing keyguard on sliding open of keyboard with non-secure keyguard");
keyguardDone(true);
}
}
/** {@inheritDoc} */
public void onSimStateChanged(SimCard.State simState) {
if (DEBUG) Log.d(TAG, "onSimStateChanged: " + simState);
switch (simState) {
case ABSENT:
// only force lock screen in case of missing sim if user hasn't
// gone through setup wizard
if (!mUpdateMonitor.isDeviceProvisioned()) {
if (!isShowing()) {
if (DEBUG) Log.d(TAG, "INTENT_VALUE_SIM_ABSENT and keygaurd isn't showing, we need "
+ "to show the keyguard since the device isn't provisioned yet.");
doKeyguard();
} else {
resetStateLocked();
}
}
break;
case PIN_REQUIRED:
case PUK_REQUIRED:
if (!isShowing()) {
if (DEBUG) Log.d(TAG, "INTENT_VALUE_SIM_LOCKED and keygaurd isn't showing, we need "
+ "to show the keyguard so the user can enter their sim pin");
doKeyguard();
} else {
resetStateLocked();
}
break;
case READY:
if (isShowing()) {
resetStateLocked();
}
break;
}
}
private BroadcastReceiver mBroadCastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(DELAYED_KEYGUARD_ACTION)) {
int sequence = intent.getIntExtra("seq", 0);
if (false) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
+ sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
if (mDelayedShowingSequence == sequence) {
doKeyguard();
}
}
}
};
/**
* When a key is received when the screen is off and the keyguard is showing,
* we need to decide whether to actually turn on the screen, and if so, tell
* the keyguard to prepare itself and poke the wake lock when it is ready.
*
* The 'Tq' suffix is per the documentation in {@link WindowManagerPolicy}.
* Be sure not to take any action that takes a long time; any significant
* action should be posted to a handler.
*
* @param keyCode The keycode of the key that woke the device
* @return Whether we poked the wake lock (and turned the screen on)
*/
public boolean onWakeKeyWhenKeyguardShowingTq(int keyCode) {
if (DEBUG) Log.d(TAG, "onWakeKeyWhenKeyguardShowing(" + keyCode + ")");
if (isWakeKeyWhenKeyguardShowing(keyCode)) {
// give the keyguard view manager a chance to adjust the state of the
// keyguard based on the key that woke the device before poking
// the wake lock
wakeWhenReadyLocked(keyCode);
return true;
} else {
return false;
}
}
private boolean isWakeKeyWhenKeyguardShowing(int keyCode) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_MUTE:
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_PLAYPAUSE:
case KeyEvent.KEYCODE_STOP:
case KeyEvent.KEYCODE_NEXTSONG:
case KeyEvent.KEYCODE_PREVIOUSSONG:
case KeyEvent.KEYCODE_REWIND:
case KeyEvent.KEYCODE_FORWARD:
case KeyEvent.KEYCODE_CAMERA:
return false;
}
return true;
}
/**
* Callbacks from {@link KeyguardViewManager}.
*/
/** {@inheritDoc} */
public void pokeWakelock() {
pokeWakelock(mKeyboardOpen ?
AWAKE_INTERVAL_DEFAULT_KEYBOARD_OPEN_MS : AWAKE_INTERVAL_DEFAULT_MS);
}
/** {@inheritDoc} */
public void pokeWakelock(int holdMs) {
synchronized (this) {
if (DBG_WAKE) Log.d(TAG, "pokeWakelock(" + holdMs + ")");
mWakeLock.acquire();
mHandler.removeMessages(TIMEOUT);
mWakelockSequence++;
Message msg = mHandler.obtainMessage(TIMEOUT, mWakelockSequence, 0);
mHandler.sendMessageDelayed(msg, holdMs);
}
}
/**
* {@inheritDoc}
*
* @see #handleKeyguardDone
*/
public void keyguardDone(boolean authenticated) {
synchronized (this) {
EventLog.writeEvent(70000, 2);
if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
Message msg = mHandler.obtainMessage(KEYGUARD_DONE);
mHandler.sendMessage(msg);
if (authenticated) {
mUpdateMonitor.clearFailedAttempts();
}
if (mExitSecureCallback != null) {
mExitSecureCallback.onKeyguardExitResult(authenticated);
mExitSecureCallback = null;
if (authenticated) {
// after succesfully exiting securely, no need to reshow
// the keyguard when they've released the lock
mExternallyEnabled = true;
mNeedToReshowWhenReenabled = false;
setStatusBarExpandable(true);
}
}
}
}
/**
* {@inheritDoc}
*
* @see #handleKeyguardDoneDrawing
*/
public void keyguardDoneDrawing() {
mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
}
/**
* This handler will be associated with the policy thread, which will also
* be the UI thread of the keyguard. Since the apis of the policy, and therefore
* this class, can be called by other threads, any action that directly
* interacts with the keyguard ui should be posted to this handler, rather
* than called directly.
*/
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case TIMEOUT:
handleTimeout(msg.arg1);
return ;
case SHOW:
handleShow();
return ;
case HIDE:
handleHide();
return ;
case RESET:
handleReset();
return ;
case VERIFY_UNLOCK:
handleVerifyUnlock();
return;
case NOTIFY_SCREEN_OFF:
handleNotifyScreenOff();
return;
case NOTIFY_SCREEN_ON:
handleNotifyScreenOn();
return;
case WAKE_WHEN_READY:
handleWakeWhenReady(msg.arg1);
return;
case KEYGUARD_DONE:
handleKeyguardDone();
return;
case KEYGUARD_DONE_DRAWING:
handleKeyguardDoneDrawing();
}
}
};
/**
* @see #keyguardDone
* @see #KEYGUARD_DONE
*/
private void handleKeyguardDone() {
if (DEBUG) Log.d(TAG, "handleKeyguardDone");
handleHide();
mPM.userActivity(SystemClock.uptimeMillis(), true);
mWakeLock.release();
}
/**
* @see #keyguardDoneDrawing
* @see #KEYGUARD_DONE_DRAWING
*/
private void handleKeyguardDoneDrawing() {
synchronized(this) {
if (false) Log.d(TAG, "handleKeyguardDoneDrawing");
if (mWaitingUntilKeyguardVisible) {
if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
mWaitingUntilKeyguardVisible = false;
notifyAll();
// there will usually be two of these sent, one as a timeout, and one
// as a result of the callback, so remove any remaining messages from
// the queue
mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
}
}
}
/**
* Handles the message sent by {@link #pokeWakelock}
* @param seq used to determine if anything has changed since the message
* was sent.
* @see #TIMEOUT
*/
private void handleTimeout(int seq) {
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleTimeout");
if (seq == mWakelockSequence) {
mWakeLock.release();
}
}
}
/**
* Handle message sent by {@link #showLocked}.
* @see #SHOW
*/
private void handleShow() {
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleShow");
if (!mSystemReady) return;
// while we're showing, we control the wake state, so ask the power
// manager not to honor request for userActivity.
mRealPowerManager.enableUserActivity(false);
mCallback.onKeyguardShow();
mKeyguardViewManager.show();
mShowing = true;
}
}
/**
* Handle message sent by {@link #hideLocked()}
* @see #HIDE
*/
private void handleHide() {
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleHide");
// When we go away, tell the poewr manager to honor requests from userActivity.
mRealPowerManager.enableUserActivity(true);
mKeyguardViewManager.hide();
mShowing = false;
}
}
/**
* Handle message sent by {@link #wakeWhenReadyLocked(int)}
* @param keyCode The key that woke the device.
* @see #WAKE_WHEN_READY
*/
private void handleWakeWhenReady(int keyCode) {
synchronized (KeyguardViewMediator.this) {
if (DBG_WAKE) Log.d(TAG, "handleWakeWhenReady(" + keyCode + ")");
// this should result in a call to 'poke wakelock' which will set a timeout
// on releasing the wakelock
mKeyguardViewManager.wakeWhenReadyTq(keyCode);
/**
* Now that the keyguard is ready and has poked the wake lock, we can
* release the handoff wakelock
*/
mWakeAndHandOff.release();
if (!mWakeLock.isHeld()) {
Log.w(TAG, "mKeyguardViewManager.wakeWhenReadyTq did not poke wake lock");
}
}
}
/**
* Handle message sent by {@link #resetStateLocked()}
* @see #RESET
*/
private void handleReset() {
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleReset");
mKeyguardViewManager.reset();
}
}
/**
* Handle message sent by {@link #verifyUnlock}
* @see #RESET
*/
private void handleVerifyUnlock() {
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
mKeyguardViewManager.verifyUnlock();
mShowing = true;
}
}
/**
* Handle message sent by {@link #notifyScreenOffLocked()}
* @see #NOTIFY_SCREEN_OFF
*/
private void handleNotifyScreenOff() {
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
mKeyguardViewManager.onScreenTurnedOff();
}
}
/**
* Handle message sent by {@link #notifyScreenOnLocked()}
* @see #NOTIFY_SCREEN_ON
*/
private void handleNotifyScreenOn() {
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
mKeyguardViewManager.onScreenTurnedOn();
}
}
}

View File

@@ -1,46 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.content.Context;
/**
* Defines operations necessary for showing a keyguard, including how to create
* it, and various properties that are useful to be able to query independant
* of whether the keyguard instance is around or not.
*/
public interface KeyguardViewProperties {
/**
* Create a keyguard view.
* @param context the context to use when creating the view.
* @param updateMonitor configuration may be based on this.
* @param controller for talking back with the containing window.
* @return the view.
*/
KeyguardViewBase createKeyguardView(Context context,
KeyguardUpdateMonitor updateMonitor,
KeyguardWindowController controller);
/**
* Would the keyguard be secure right now?
* @return Whether the keyguard is currently secure, meaning it will block
* the user from getting past it until the user enters some sort of PIN.
*/
boolean isSecure();
}

View File

@@ -1,29 +0,0 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
/**
* Interface passed to the keyguard view, for it to call up to control
* its containing window.
*/
public interface KeyguardWindowController {
/**
* Control whether the window needs input -- that is if it has
* text fields and thus should allow input method interaction.
*/
void setNeedsInput(boolean needsInput);
}

View File

@@ -1,570 +0,0 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.accounts.AccountsServiceConstants;
import android.accounts.IAccountsService;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.SystemProperties;
import com.android.internal.telephony.SimCard;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import com.android.internal.R;
import com.android.internal.widget.LockPatternUtils;
/**
* The host view for all of the screens of the pattern unlock screen. There are
* two {@link Mode}s of operation, lock and unlock. This will show the appropriate
* screen, and listen for callbacks via {@link com.android.internal.policy.impl.KeyguardScreenCallback
* from the current screen.
*
* This view, in turn, communicates back to {@link com.android.internal.policy.impl.KeyguardViewManager}
* via its {@link com.android.internal.policy.impl.KeyguardViewCallback}, as appropriate.
*/
public class LockPatternKeyguardView extends KeyguardViewBase {
// intent action for launching emergency dialer activity.
static final String ACTION_EMERGENCY_DIAL = "com.android.phone.EmergencyDialer.DIAL";
private static final boolean DEBUG = false;
private static final String TAG = "LockPatternKeyguardView";
private final KeyguardUpdateMonitor mUpdateMonitor;
private final KeyguardWindowController mWindowController;
private View mLockScreen;
private View mUnlockScreen;
private boolean mScreenOn = false;
private boolean mHasAccount = false; // assume they don't have an account until we know better
/**
* The current {@link KeyguardScreen} will use this to communicate back to us.
*/
KeyguardScreenCallback mKeyguardScreenCallback;
private boolean mRequiresSim;
/**
* Either a lock screen (an informational keyguard screen), or an unlock
* screen (a means for unlocking the device) is shown at any given time.
*/
enum Mode {
LockScreen,
UnlockScreen
}
/**
* The different types screens available for {@link Mode#UnlockScreen}.
* @see com.android.internal.policy.impl.LockPatternKeyguardView#getUnlockMode()
*/
enum UnlockMode {
/**
* Unlock by drawing a pattern.
*/
Pattern,
/**
* Unlock by entering a sim pin.
*/
SimPin,
/**
* Unlock by entering an account's login and password.
*/
Account
}
/**
* The current mode.
*/
private Mode mMode = Mode.LockScreen;
/**
* Keeps track of what mode the current unlock screen is
*/
private UnlockMode mUnlockScreenMode;
/**
* If true, it means we are in the process of verifying that the user
* can get past the lock screen per {@link #verifyUnlock()}
*/
private boolean mIsVerifyUnlockOnly = false;
/**
* Used to lookup the state of the lock pattern
*/
private final LockPatternUtils mLockPatternUtils;
/**
* Used to fetch accounts from GLS.
*/
private ServiceConnection mServiceConnection;
/**
* @return Whether we are stuck on the lock screen because the sim is
* missing.
*/
private boolean stuckOnLockScreenBecauseSimMissing() {
return mRequiresSim
&& (!mUpdateMonitor.isDeviceProvisioned())
&& (mUpdateMonitor.getSimState() == SimCard.State.ABSENT);
}
/**
* @param context Used to inflate, and create views.
* @param updateMonitor Knows the state of the world, and passed along to each
* screen so they can use the knowledge, and also register for callbacks
* on dynamic information.
* @param lockPatternUtils Used to look up state of lock pattern.
*/
public LockPatternKeyguardView(
Context context,
KeyguardUpdateMonitor updateMonitor,
LockPatternUtils lockPatternUtils,
KeyguardWindowController controller) {
super(context);
asyncCheckForAccount();
mRequiresSim =
TextUtils.isEmpty(SystemProperties.get("keyguard.no_require_sim"));
mUpdateMonitor = updateMonitor;
mLockPatternUtils = lockPatternUtils;
mWindowController = controller;
mMode = getInitialMode();
mKeyguardScreenCallback = new KeyguardScreenCallback() {
public void goToLockScreen() {
if (mIsVerifyUnlockOnly) {
// navigating away from unlock screen during verify mode means
// we are done and the user failed to authenticate.
mIsVerifyUnlockOnly = false;
getCallback().keyguardDone(false);
} else {
updateScreen(Mode.LockScreen);
}
}
public void goToUnlockScreen() {
final SimCard.State simState = mUpdateMonitor.getSimState();
if (stuckOnLockScreenBecauseSimMissing()
|| (simState == SimCard.State.PUK_REQUIRED)){
// stuck on lock screen when sim missing or puk'd
return;
}
if (!isSecure()) {
getCallback().keyguardDone(true);
} else {
updateScreen(Mode.UnlockScreen);
}
}
public boolean isSecure() {
return LockPatternKeyguardView.this.isSecure();
}
public boolean isVerifyUnlockOnly() {
return mIsVerifyUnlockOnly;
}
public void recreateMe() {
recreateScreens();
}
public void takeEmergencyCallAction() {
Intent intent = new Intent(ACTION_EMERGENCY_DIAL);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
getContext().startActivity(intent);
}
public void pokeWakelock() {
getCallback().pokeWakelock();
}
public void pokeWakelock(int millis) {
getCallback().pokeWakelock(millis);
}
public void keyguardDone(boolean authenticated) {
getCallback().keyguardDone(authenticated);
}
public void keyguardDoneDrawing() {
// irrelevant to keyguard screen, they shouldn't be calling this
}
public void reportFailedPatternAttempt() {
mUpdateMonitor.reportFailedAttempt();
final int failedAttempts = mUpdateMonitor.getFailedAttempts();
if (mHasAccount && failedAttempts ==
(LockPatternUtils.FAILED_ATTEMPTS_BEFORE_RESET
- LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT)) {
showAlmostAtAccountLoginDialog();
} else if (mHasAccount && failedAttempts >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_RESET) {
mLockPatternUtils.setPermanentlyLocked(true);
updateScreen(mMode);
} else if ((failedAttempts % LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT)
== 0) {
showTimeoutDialog();
}
}
public boolean doesFallbackUnlockScreenExist() {
return mHasAccount;
}
};
/**
* We'll get key events the current screen doesn't use. see
* {@link KeyguardViewBase#onKeyDown(int, android.view.KeyEvent)}
*/
setFocusableInTouchMode(true);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
// create both the lock and unlock screen so they are quickly available
// when the screen turns on
mLockScreen = createLockScreen();
addView(mLockScreen);
final UnlockMode unlockMode = getUnlockMode();
mUnlockScreen = createUnlockScreenFor(unlockMode);
mUnlockScreenMode = unlockMode;
addView(mUnlockScreen);
updateScreen(mMode);
}
/**
* Asynchronously checks for at least one account. This will set mHasAccount
* to true if an account is found.
*/
private void asyncCheckForAccount() {
mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
try {
IAccountsService accountsService = IAccountsService.Stub.asInterface(service);
String accounts[] = accountsService.getAccounts();
mHasAccount = (accounts.length > 0);
} catch (RemoteException e) {
// Not much we can do here...
Log.e(TAG, "Gls died while attempting to get accounts: " + e);
} finally {
getContext().unbindService(mServiceConnection);
mServiceConnection = null;
}
}
public void onServiceDisconnected(ComponentName className) {
// nothing to do here
}
};
boolean status = getContext().bindService(AccountsServiceConstants.SERVICE_INTENT,
mServiceConnection, Context.BIND_AUTO_CREATE);
if (!status) Log.e(TAG, "Failed to bind to GLS while checking for account");
}
@Override
public void reset() {
mIsVerifyUnlockOnly = false;
updateScreen(getInitialMode());
}
@Override
public void onScreenTurnedOff() {
mScreenOn = false;
if (mMode == Mode.LockScreen) {
((KeyguardScreen) mLockScreen).onPause();
} else {
((KeyguardScreen) mUnlockScreen).onPause();
}
}
@Override
public void onScreenTurnedOn() {
mScreenOn = true;
if (mMode == Mode.LockScreen) {
((KeyguardScreen) mLockScreen).onResume();
} else {
((KeyguardScreen) mUnlockScreen).onResume();
}
}
private void recreateScreens() {
if (mLockScreen.getVisibility() == View.VISIBLE) {
((KeyguardScreen) mLockScreen).onPause();
}
((KeyguardScreen) mLockScreen).cleanUp();
removeViewInLayout(mLockScreen);
mLockScreen = createLockScreen();
mLockScreen.setVisibility(View.INVISIBLE);
addView(mLockScreen);
if (mUnlockScreen.getVisibility() == View.VISIBLE) {
((KeyguardScreen) mUnlockScreen).onPause();
}
((KeyguardScreen) mUnlockScreen).cleanUp();
removeViewInLayout(mUnlockScreen);
final UnlockMode unlockMode = getUnlockMode();
mUnlockScreen = createUnlockScreenFor(unlockMode);
mUnlockScreen.setVisibility(View.INVISIBLE);
mUnlockScreenMode = unlockMode;
addView(mUnlockScreen);
updateScreen(mMode);
}
@Override
public void wakeWhenReadyTq(int keyCode) {
if (DEBUG) Log.d(TAG, "onWakeKey");
if (keyCode == KeyEvent.KEYCODE_MENU && isSecure() && (mMode == Mode.LockScreen)
&& (mUpdateMonitor.getSimState() != SimCard.State.PUK_REQUIRED)) {
if (DEBUG) Log.d(TAG, "switching screens to unlock screen because wake key was MENU");
updateScreen(Mode.UnlockScreen);
getCallback().pokeWakelock();
} else {
if (DEBUG) Log.d(TAG, "poking wake lock immediately");
getCallback().pokeWakelock();
}
}
@Override
public void verifyUnlock() {
if (!isSecure()) {
// non-secure keyguard screens are successfull by default
getCallback().keyguardDone(true);
} else if (mUnlockScreenMode != UnlockMode.Pattern) {
// can only verify unlock when in pattern mode
getCallback().keyguardDone(false);
} else {
// otherwise, go to the unlock screen, see if they can verify it
mIsVerifyUnlockOnly = true;
updateScreen(Mode.UnlockScreen);
}
}
@Override
public void cleanUp() {
((KeyguardScreen) mLockScreen).onPause();
((KeyguardScreen) mLockScreen).cleanUp();
((KeyguardScreen) mUnlockScreen).onPause();
((KeyguardScreen) mUnlockScreen).cleanUp();
}
private boolean isSecure() {
UnlockMode unlockMode = getUnlockMode();
if (unlockMode == UnlockMode.Pattern) {
return mLockPatternUtils.isLockPatternEnabled();
} else if (unlockMode == UnlockMode.SimPin) {
return mUpdateMonitor.getSimState() == SimCard.State.PIN_REQUIRED
|| mUpdateMonitor.getSimState() == SimCard.State.PUK_REQUIRED;
} else if (unlockMode == UnlockMode.Account) {
return true;
} else {
throw new IllegalStateException("unknown unlock mode " + unlockMode);
}
}
private void updateScreen(final Mode mode) {
mMode = mode;
final View goneScreen = (mode == Mode.LockScreen) ? mUnlockScreen : mLockScreen;
final View visibleScreen = (mode == Mode.LockScreen)
? mLockScreen : getUnlockScreenForCurrentUnlockMode();
if (mScreenOn) {
if (goneScreen.getVisibility() == View.VISIBLE) {
((KeyguardScreen) goneScreen).onPause();
}
if (visibleScreen.getVisibility() != View.VISIBLE) {
((KeyguardScreen) visibleScreen).onResume();
}
}
goneScreen.setVisibility(View.GONE);
visibleScreen.setVisibility(View.VISIBLE);
mWindowController.setNeedsInput(((KeyguardScreen)visibleScreen).needsInput());
if (!visibleScreen.requestFocus()) {
throw new IllegalStateException("keyguard screen must be able to take "
+ "focus when shown " + visibleScreen.getClass().getCanonicalName());
}
}
View createLockScreen() {
return new LockScreen(
mContext,
mLockPatternUtils,
mUpdateMonitor,
mKeyguardScreenCallback);
}
View createUnlockScreenFor(UnlockMode unlockMode) {
if (unlockMode == UnlockMode.Pattern) {
return new UnlockScreen(
mContext,
mLockPatternUtils,
mUpdateMonitor,
mKeyguardScreenCallback,
mUpdateMonitor.getFailedAttempts());
} else if (unlockMode == UnlockMode.SimPin) {
return new SimUnlockScreen(
mContext,
mUpdateMonitor,
mKeyguardScreenCallback);
} else if (unlockMode == UnlockMode.Account) {
try {
return new AccountUnlockScreen(
mContext,
mKeyguardScreenCallback,
mLockPatternUtils);
} catch (IllegalStateException e) {
Log.i(TAG, "Couldn't instantiate AccountUnlockScreen"
+ " (IAccountsService isn't available)");
// TODO: Need a more general way to provide a
// platform-specific fallback UI here.
// For now, if we can't display the account login
// unlock UI, just bring back the regular "Pattern" unlock mode.
// (We do this by simply returning a regular UnlockScreen
// here. This means that the user will still see the
// regular pattern unlock UI, regardless of the value of
// mUnlockScreenMode or whether or not we're in the
// "permanently locked" state.)
return createUnlockScreenFor(UnlockMode.Pattern);
}
} else {
throw new IllegalArgumentException("unknown unlock mode " + unlockMode);
}
}
private View getUnlockScreenForCurrentUnlockMode() {
final UnlockMode unlockMode = getUnlockMode();
// if a screen exists for the correct mode, we're done
if (unlockMode == mUnlockScreenMode) {
return mUnlockScreen;
}
// remember the mode
mUnlockScreenMode = unlockMode;
// unlock mode has changed and we have an existing old unlock screen
// to clean up
if (mScreenOn && (mUnlockScreen.getVisibility() == View.VISIBLE)) {
((KeyguardScreen) mUnlockScreen).onPause();
}
((KeyguardScreen) mUnlockScreen).cleanUp();
removeViewInLayout(mUnlockScreen);
// create the new one
mUnlockScreen = createUnlockScreenFor(unlockMode);
mUnlockScreen.setVisibility(View.INVISIBLE);
addView(mUnlockScreen);
return mUnlockScreen;
}
/**
* Given the current state of things, what should be the initial mode of
* the lock screen (lock or unlock).
*/
private Mode getInitialMode() {
final SimCard.State simState = mUpdateMonitor.getSimState();
if (stuckOnLockScreenBecauseSimMissing() || (simState == SimCard.State.PUK_REQUIRED)) {
return Mode.LockScreen;
} else if (mUpdateMonitor.isKeyboardOpen() && isSecure()) {
return Mode.UnlockScreen;
} else {
return Mode.LockScreen;
}
}
/**
* Given the current state of things, what should the unlock screen be?
*/
private UnlockMode getUnlockMode() {
final SimCard.State simState = mUpdateMonitor.getSimState();
if (simState == SimCard.State.PIN_REQUIRED || simState == SimCard.State.PUK_REQUIRED) {
return UnlockMode.SimPin;
} else {
return mLockPatternUtils.isPermanentlyLocked() ?
UnlockMode.Account:
UnlockMode.Pattern;
}
}
private void showTimeoutDialog() {
int timeoutInSeconds = (int) LockPatternUtils.FAILED_ATTEMPT_TIMEOUT_MS / 1000;
String message = mContext.getString(
R.string.lockscreen_too_many_failed_attempts_dialog_message,
mUpdateMonitor.getFailedAttempts(),
timeoutInSeconds);
final AlertDialog dialog = new AlertDialog.Builder(mContext)
.setTitle(null)
.setMessage(message)
.setNeutralButton(R.string.ok, null)
.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
dialog.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
dialog.show();
}
private void showAlmostAtAccountLoginDialog() {
int timeoutInSeconds = (int) LockPatternUtils.FAILED_ATTEMPT_TIMEOUT_MS / 1000;
String message = mContext.getString(
R.string.lockscreen_failed_attempts_almost_glogin,
LockPatternUtils.FAILED_ATTEMPTS_BEFORE_RESET - LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT,
LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT,
timeoutInSeconds);
final AlertDialog dialog = new AlertDialog.Builder(mContext)
.setTitle(null)
.setMessage(message)
.setNeutralButton(R.string.ok, null)
.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
dialog.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
dialog.show();
}
}

View File

@@ -1,67 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import com.android.internal.widget.LockPatternUtils;
import android.content.Context;
import com.android.internal.telephony.SimCard;
/**
* Knows how to create a lock pattern keyguard view, and answer questions about
* it (even if it hasn't been created, per the interface specs).
*/
public class LockPatternKeyguardViewProperties implements KeyguardViewProperties {
private final LockPatternUtils mLockPatternUtils;
private final KeyguardUpdateMonitor mUpdateMonitor;
/**
* @param lockPatternUtils Used to know whether the pattern enabled, and passed
* onto the keygaurd view when it is created.
* @param updateMonitor Used to know whether the sim pin is enabled, and passed
* onto the keyguard view when it is created.
*/
public LockPatternKeyguardViewProperties(LockPatternUtils lockPatternUtils,
KeyguardUpdateMonitor updateMonitor) {
mLockPatternUtils = lockPatternUtils;
mUpdateMonitor = updateMonitor;
}
public KeyguardViewBase createKeyguardView(Context context,
KeyguardUpdateMonitor updateMonitor,
KeyguardWindowController controller) {
return new LockPatternKeyguardView(context, updateMonitor,
mLockPatternUtils, controller);
}
public boolean isSecure() {
return isLockPatternSecure() || isSimPinSecure();
}
private boolean isLockPatternSecure() {
return mLockPatternUtils.isLockPatternEnabled() && mLockPatternUtils
.savedPatternExists();
}
private boolean isSimPinSecure() {
final SimCard.State simState = mUpdateMonitor.getSimState();
return (simState == SimCard.State.PIN_REQUIRED || simState == SimCard.State.PUK_REQUIRED
|| simState == SimCard.State.ABSENT);
}
}

View File

@@ -1,371 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import com.android.internal.R;
import com.android.internal.widget.LockPatternUtils;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.internal.telephony.SimCard;
import java.util.Date;
/**
* The screen within {@link LockPatternKeyguardView} that shows general
* information about the device depending on its state, and how to get
* past it, as applicable.
*/
class LockScreen extends LinearLayout implements KeyguardScreen, KeyguardUpdateMonitor.InfoCallback,
KeyguardUpdateMonitor.SimStateCallback, KeyguardUpdateMonitor.ConfigurationChangeCallback {
private final LockPatternUtils mLockPatternUtils;
private final KeyguardUpdateMonitor mUpdateMonitor;
private final KeyguardScreenCallback mCallback;
private TextView mHeaderSimOk1;
private TextView mHeaderSimOk2;
private TextView mHeaderSimBad1;
private TextView mHeaderSimBad2;
private TextView mTime;
private TextView mDate;
private ViewGroup mBatteryInfoGroup;
private ImageView mBatteryInfoIcon;
private TextView mBatteryInfoText;
private View mBatteryInfoSpacer;
private ViewGroup mNextAlarmGroup;
private TextView mAlarmText;
private View mAlarmSpacer;
private ViewGroup mScreenLockedMessageGroup;
private TextView mLockInstructions;
private Button mEmergencyCallButton;
/**
* false means sim is missing or PUK'd
*/
private boolean mSimOk = true;
// are we showing battery information?
private boolean mShowingBatteryInfo = false;
// last known plugged in state
private boolean mPluggedIn = false;
// last known battery level
private int mBatteryLevel = 100;
private View[] mOnlyVisibleWhenSimOk;
private View[] mOnlyVisibleWhenSimNotOk;
/**
* @param context Used to setup the view.
* @param lockPatternUtils Used to know the state of the lock pattern settings.
* @param updateMonitor Used to register for updates on various keyguard related
* state, and query the initial state at setup.
* @param callback Used to communicate back to the host keyguard view.
*/
LockScreen(Context context, LockPatternUtils lockPatternUtils,
KeyguardUpdateMonitor updateMonitor,
KeyguardScreenCallback callback) {
super(context);
mLockPatternUtils = lockPatternUtils;
mUpdateMonitor = updateMonitor;
mCallback = callback;
final LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.keyguard_screen_lock, this, true);
mSimOk = isSimOk(updateMonitor.getSimState());
mShowingBatteryInfo = updateMonitor.shouldShowBatteryInfo();
mPluggedIn = updateMonitor.isDevicePluggedIn();
mBatteryLevel = updateMonitor.getBatteryLevel();
mHeaderSimOk1 = (TextView) findViewById(R.id.headerSimOk1);
mHeaderSimOk2 = (TextView) findViewById(R.id.headerSimOk2);
mHeaderSimBad1 = (TextView) findViewById(R.id.headerSimBad1);
mHeaderSimBad2 = (TextView) findViewById(R.id.headerSimBad2);
mTime = (TextView) findViewById(R.id.time);
mDate = (TextView) findViewById(R.id.date);
mBatteryInfoGroup = (ViewGroup) findViewById(R.id.batteryInfo);
mBatteryInfoIcon = (ImageView) findViewById(R.id.batteryInfoIcon);
mBatteryInfoText = (TextView) findViewById(R.id.batteryInfoText);
mBatteryInfoSpacer = findViewById(R.id.batteryInfoSpacer);
mNextAlarmGroup = (ViewGroup) findViewById(R.id.nextAlarmInfo);
mAlarmText = (TextView) findViewById(R.id.nextAlarmText);
mAlarmSpacer = findViewById(R.id.nextAlarmSpacer);
mScreenLockedMessageGroup = (ViewGroup) findViewById(R.id.screenLockedInfo);
mLockInstructions = (TextView) findViewById(R.id.lockInstructions);
mEmergencyCallButton = (Button) findViewById(R.id.emergencyCallButton);
mEmergencyCallButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallback.takeEmergencyCallAction();
}
});
mOnlyVisibleWhenSimOk = new View[] {
mHeaderSimOk1,
mHeaderSimOk2,
mBatteryInfoGroup,
mBatteryInfoSpacer,
mNextAlarmGroup,
mAlarmSpacer,
mScreenLockedMessageGroup,
mLockInstructions
};
mOnlyVisibleWhenSimNotOk = new View[] {
mHeaderSimBad1,
mHeaderSimBad2,
mEmergencyCallButton
};
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
refreshBatteryDisplay();
refreshAlarmDisplay();
refreshTimeAndDateDisplay();
refreshUnlockIntructions();
refreshViewsWRTSimOk();
refreshSimOkHeaders(mUpdateMonitor.getTelephonyPlmn(), mUpdateMonitor.getTelephonySpn());
updateMonitor.registerInfoCallback(this);
updateMonitor.registerSimStateCallback(this);
updateMonitor.registerConfigurationChangeCallback(this);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
mCallback.goToUnlockScreen();
}
return false;
}
private void refreshViewsWRTSimOk() {
if (mSimOk) {
for (int i = 0; i < mOnlyVisibleWhenSimOk.length; i++) {
final View view = mOnlyVisibleWhenSimOk[i];
if (view == null) throw new RuntimeException("index " + i + " null");
view.setVisibility(View.VISIBLE);
}
for (int i = 0; i < mOnlyVisibleWhenSimNotOk.length; i++) {
final View view = mOnlyVisibleWhenSimNotOk[i];
view.setVisibility(View.GONE);
}
refreshSimOkHeaders(mUpdateMonitor.getTelephonyPlmn(), mUpdateMonitor.getTelephonySpn());
refreshAlarmDisplay();
refreshBatteryDisplay();
} else {
for (int i = 0; i < mOnlyVisibleWhenSimOk.length; i++) {
final View view = mOnlyVisibleWhenSimOk[i];
view.setVisibility(View.GONE);
}
for (int i = 0; i < mOnlyVisibleWhenSimNotOk.length; i++) {
final View view = mOnlyVisibleWhenSimNotOk[i];
view.setVisibility(View.VISIBLE);
}
refreshSimBadInfo();
}
}
private void refreshSimBadInfo() {
final SimCard.State simState = mUpdateMonitor.getSimState();
if (simState == SimCard.State.PUK_REQUIRED) {
mHeaderSimBad1.setText(R.string.lockscreen_sim_puk_locked_message);
mHeaderSimBad2.setText(R.string.lockscreen_sim_puk_locked_instructions);
} else if (simState == SimCard.State.ABSENT) {
mHeaderSimBad1.setText(R.string.lockscreen_missing_sim_message);
mHeaderSimBad2.setVisibility(View.GONE);
//mHeaderSimBad2.setText(R.string.lockscreen_missing_sim_instructions);
} else {
mHeaderSimBad1.setVisibility(View.GONE);
mHeaderSimBad2.setVisibility(View.GONE);
}
}
private void refreshUnlockIntructions() {
if (mLockPatternUtils.isLockPatternEnabled()
|| mUpdateMonitor.getSimState() == SimCard.State.PIN_REQUIRED) {
mLockInstructions.setText(R.string.lockscreen_instructions_when_pattern_enabled);
} else {
mLockInstructions.setText(R.string.lockscreen_instructions_when_pattern_disabled);
}
}
private void refreshAlarmDisplay() {
String nextAlarmText = mLockPatternUtils.getNextAlarm();
if (nextAlarmText != null && mSimOk) {
setAlarmInfoVisible(true);
mAlarmText.setText(nextAlarmText);
} else {
setAlarmInfoVisible(false);
}
}
private void setAlarmInfoVisible(boolean visible) {
final int visibilityFlag = visible ? View.VISIBLE : View.GONE;
mNextAlarmGroup.setVisibility(visibilityFlag);
mAlarmSpacer.setVisibility(visibilityFlag);
}
public void onRefreshBatteryInfo(boolean showBatteryInfo, boolean pluggedIn,
int batteryLevel) {
mShowingBatteryInfo = showBatteryInfo;
mPluggedIn = pluggedIn;
mBatteryLevel = batteryLevel;
refreshBatteryDisplay();
}
private void refreshBatteryDisplay() {
if (!mShowingBatteryInfo || !mSimOk) {
mBatteryInfoGroup.setVisibility(View.GONE);
mBatteryInfoSpacer.setVisibility(View.GONE);
return;
}
mBatteryInfoGroup.setVisibility(View.VISIBLE);
mBatteryInfoSpacer.setVisibility(View.VISIBLE);
if (mPluggedIn) {
mBatteryInfoIcon.setImageResource(R.drawable.ic_lock_idle_charging);
mBatteryInfoText.setText(
getContext().getString(R.string.lockscreen_plugged_in, mBatteryLevel));
} else {
mBatteryInfoIcon.setImageResource(R.drawable.ic_lock_idle_low_battery);
mBatteryInfoText.setText(R.string.lockscreen_low_battery);
}
}
public void onTimeChanged() {
refreshTimeAndDateDisplay();
}
private void refreshTimeAndDateDisplay() {
Date now = new Date();
mTime.setText(DateFormat.getTimeFormat(getContext()).format(now));
mDate.setText(DateFormat.getDateFormat(getContext()).format(now));
}
public void onRefreshCarrierInfo(CharSequence plmn, CharSequence spn) {
refreshSimOkHeaders(plmn, spn);
}
private void refreshSimOkHeaders(CharSequence plmn, CharSequence spn) {
final SimCard.State simState = mUpdateMonitor.getSimState();
if (simState == SimCard.State.READY) {
if (plmn != null) {
mHeaderSimOk1.setVisibility(View.VISIBLE);
mHeaderSimOk1.setText(plmn);
} else {
mHeaderSimOk1.setVisibility(View.GONE);
}
if (spn != null) {
mHeaderSimOk2.setVisibility(View.VISIBLE);
mHeaderSimOk2.setText(spn);
} else {
mHeaderSimOk2.setVisibility(View.GONE);
}
} else if (simState == SimCard.State.PIN_REQUIRED) {
mHeaderSimOk1.setVisibility(View.VISIBLE);
mHeaderSimOk1.setText(R.string.lockscreen_sim_locked_message);
mHeaderSimOk2.setVisibility(View.GONE);
} else if (simState == SimCard.State.ABSENT) {
mHeaderSimOk1.setVisibility(View.VISIBLE);
mHeaderSimOk1.setText(R.string.lockscreen_missing_sim_message_short);
mHeaderSimOk2.setVisibility(View.GONE);
} else if (simState == SimCard.State.NETWORK_LOCKED) {
mHeaderSimOk1.setVisibility(View.VISIBLE);
mHeaderSimOk1.setText(R.string.lockscreen_network_locked_message);
mHeaderSimOk2.setVisibility(View.GONE);
}
}
public void onSimStateChanged(SimCard.State simState) {
mSimOk = isSimOk(simState);
refreshViewsWRTSimOk();
}
/**
* @return Whether the sim state is ok, meaning we don't need to show
* a special screen with the emergency call button and keep them from
* doing anything else.
*/
private boolean isSimOk(SimCard.State simState) {
boolean missingAndNotProvisioned = (!mUpdateMonitor.isDeviceProvisioned()
&& simState == SimCard.State.ABSENT);
return !(missingAndNotProvisioned || simState == SimCard.State.PUK_REQUIRED);
}
public void onOrientationChange(boolean inPortrait) {
}
public void onKeyboardChange(boolean isKeyboardOpen) {
if (isKeyboardOpen) {
mCallback.goToUnlockScreen();
}
}
/** {@inheritDoc} */
public boolean needsInput() {
return false;
}
/** {@inheritDoc} */
public void onPause() {
}
/** {@inheritDoc} */
public void onResume() {
}
/** {@inheritDoc} */
public void cleanUp() {
mUpdateMonitor.removeCallback(this);
}
}

View File

@@ -1,73 +0,0 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import java.util.Map;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.LayoutInflater;
public class PhoneLayoutInflater extends LayoutInflater {
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit."
};
/**
* Instead of instantiating directly, you should retrieve an instance
* through {@link Context#getSystemService}
*
* @param context The Context in which in which to find resources and other
* application-specific things.
*
* @see Context#getSystemService
*/
public PhoneLayoutInflater(Context context) {
super(context);
}
protected PhoneLayoutInflater(LayoutInflater original, Context newContext) {
super(original, newContext);
}
/** Override onCreateView to instantiate names that correspond to the
widgets known to the Widget factory. If we don't find a match,
call through to our super class.
*/
@Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
for (String prefix : sClassPrefixList) {
try {
View view = createView(name, prefix, attrs);
if (view != null) {
return view;
}
} catch (ClassNotFoundException e) {
// In this case we want to let the base class take a crack
// at it.
}
}
return super.onCreateView(name, attrs);
}
public LayoutInflater cloneInContext(Context newContext) {
return new PhoneLayoutInflater(this, newContext);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,69 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.content.Context;
import android.util.Log;
import com.android.internal.policy.IPolicy;
import com.android.internal.policy.impl.PhoneLayoutInflater;
import com.android.internal.policy.impl.PhoneWindow;
import com.android.internal.policy.impl.PhoneWindowManager;
/**
* {@hide}
*/
// Simple implementation of the policy interface that spawns the right
// set of objects
public class Policy implements IPolicy {
private static final String TAG = "PhonePolicy";
private static final String[] preload_classes = {
"com.android.internal.policy.impl.PhoneLayoutInflater",
"com.android.internal.policy.impl.PhoneWindow",
"com.android.internal.policy.impl.PhoneWindow$1",
"com.android.internal.policy.impl.PhoneWindow$ContextMenuCallback",
"com.android.internal.policy.impl.PhoneWindow$DecorView",
"com.android.internal.policy.impl.PhoneWindow$PanelFeatureState",
"com.android.internal.policy.impl.PhoneWindow$PanelFeatureState$SavedState",
};
static {
// For performance reasons, preload some policy specific classes when
// the policy gets loaded.
for (String s : preload_classes) {
try {
Class.forName(s);
} catch (ClassNotFoundException ex) {
Log.e(TAG, "Could not preload class for phone policy: " + s);
}
}
}
public PhoneWindow makeNewWindow(Context context) {
return new PhoneWindow(context);
}
public PhoneLayoutInflater makeNewLayoutInflater(Context context) {
return new PhoneLayoutInflater(context);
}
public PhoneWindowManager makeNewWindowManager() {
return new PhoneWindowManager();
}
}

View File

@@ -1,179 +0,0 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import com.android.internal.R;
import android.app.Dialog;
import android.app.StatusBarManager;
import android.content.Context;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.IServiceManager;
import android.os.LocalPowerManager;
import android.os.ServiceManager;
import android.os.ServiceManagerNative;
import android.os.SystemClock;
import com.android.internal.telephony.ITelephony;
import android.view.KeyEvent;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
/**
* @deprecated use {@link GlobalActions} instead.
*/
public class PowerDialog extends Dialog implements OnClickListener,
OnKeyListener {
private static final String TAG = "PowerDialog";
static private StatusBarManager sStatusBar;
private Button mKeyguard;
private Button mPower;
private Button mRadioPower;
private Button mSilent;
private LocalPowerManager mPowerManager;
public PowerDialog(Context context, LocalPowerManager powerManager) {
super(context);
mPowerManager = powerManager;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getContext();
if (sStatusBar == null) {
sStatusBar = (StatusBarManager)context.getSystemService(Context.STATUS_BAR_SERVICE);
}
setContentView(com.android.internal.R.layout.power_dialog);
getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
setTitle(context.getText(R.string.power_dialog));
mKeyguard = (Button) findViewById(R.id.keyguard);
mPower = (Button) findViewById(R.id.off);
mRadioPower = (Button) findViewById(R.id.radio_power);
mSilent = (Button) findViewById(R.id.silent);
if (mKeyguard != null) {
mKeyguard.setOnKeyListener(this);
mKeyguard.setOnClickListener(this);
}
if (mPower != null) {
mPower.setOnClickListener(this);
}
if (mRadioPower != null) {
mRadioPower.setOnClickListener(this);
}
if (mSilent != null) {
mSilent.setOnClickListener(this);
// XXX: HACK for now hide the silent until we get mute support
mSilent.setVisibility(View.GONE);
}
CharSequence text;
// set the keyguard button's text
text = context.getText(R.string.screen_lock);
mKeyguard.setText(text);
mKeyguard.requestFocus();
try {
ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
if (phone != null) {
text = phone.isRadioOn() ? context
.getText(R.string.turn_off_radio) : context
.getText(R.string.turn_on_radio);
}
} catch (RemoteException ex) {
// ignore it
}
mRadioPower.setText(text);
}
public void onClick(View v) {
this.dismiss();
if (v == mPower) {
// shutdown by making sure radio and power are handled accordingly.
ShutdownThread.shutdownAfterDisablingRadio(getContext(), true);
} else if (v == mRadioPower) {
try {
ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
if (phone != null) {
phone.toggleRadioOnOff();
}
} catch (RemoteException ex) {
// ignore it
}
} else if (v == mSilent) {
// do something
} else if (v == mKeyguard) {
if (v.isInTouchMode()) {
// only in touch mode for the reasons explained in onKey.
this.dismiss();
mPowerManager.goToSleep(SystemClock.uptimeMillis() + 1);
}
}
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
// The activate keyguard button needs to put the device to sleep on the
// key up event. If we try to put it to sleep on the click or down
// action
// the the up action will cause the device to wake back up.
// Log.i(TAG, "keyCode: " + keyCode + " action: " + event.getAction());
if (keyCode != KeyEvent.KEYCODE_DPAD_CENTER
|| event.getAction() != KeyEvent.ACTION_UP) {
// Log.i(TAG, "getting out of dodge...");
return false;
}
// Log.i(TAG, "Clicked mKeyguard! dimissing dialog");
this.dismiss();
// Log.i(TAG, "onKey: turning off the screen...");
// XXX: This is a hack for now
mPowerManager.goToSleep(event.getEventTime() + 1);
return true;
}
public void show() {
super.show();
Log.d(TAG, "show... disabling expand");
sStatusBar.disable(StatusBarManager.DISABLE_EXPAND);
}
public void dismiss() {
super.dismiss();
Log.d(TAG, "dismiss... reenabling expand");
sStatusBar.disable(StatusBarManager.DISABLE_NONE);
}
}

View File

@@ -1,255 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.StatusBarManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class RecentApplicationsDialog extends Dialog implements OnClickListener {
// Elements for debugging support
// private static final String LOG_TAG = "RecentApplicationsDialog";
private static final boolean DBG_FORCE_EMPTY_LIST = false;
static private StatusBarManager sStatusBar;
private static final int NUM_BUTTONS = 6;
private static final int MAX_RECENT_TASKS = NUM_BUTTONS * 2; // allow for some discards
final View[] mButtons = new View[NUM_BUTTONS];
View mNoAppsText;
IntentFilter mBroadcastIntentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
public RecentApplicationsDialog(Context context) {
super(context);
}
/**
* We create the recent applications dialog just once, and it stays around (hidden)
* until activated by the user.
*
* @see PhoneWindowManager#showRecentAppsDialog
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getContext();
if (sStatusBar == null) {
sStatusBar = (StatusBarManager)context.getSystemService(Context.STATUS_BAR_SERVICE);
}
Window theWindow = getWindow();
theWindow.requestFeature(Window.FEATURE_NO_TITLE);
theWindow.setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
theWindow.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
theWindow.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
setContentView(com.android.internal.R.layout.recent_apps_dialog);
mButtons[0] = findViewById(com.android.internal.R.id.button1);
mButtons[1] = findViewById(com.android.internal.R.id.button2);
mButtons[2] = findViewById(com.android.internal.R.id.button3);
mButtons[3] = findViewById(com.android.internal.R.id.button4);
mButtons[4] = findViewById(com.android.internal.R.id.button5);
mButtons[5] = findViewById(com.android.internal.R.id.button6);
mNoAppsText = findViewById(com.android.internal.R.id.no_applications_message);
for (View b : mButtons) {
b.setOnClickListener(this);
}
}
/**
* Handler for user clicks. If a button was clicked, launch the corresponding activity.
*/
public void onClick(View v) {
for (View b : mButtons) {
if (b == v) {
// prepare a launch intent and send it
Intent intent = (Intent)b.getTag();
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
getContext().startActivity(intent);
}
}
dismiss();
}
/**
* Set up and show the recent activities dialog.
*/
@Override
public void onStart() {
super.onStart();
reloadButtons();
if (sStatusBar != null) {
sStatusBar.disable(StatusBarManager.DISABLE_EXPAND);
}
// receive broadcasts
getContext().registerReceiver(mBroadcastReceiver, mBroadcastIntentFilter);
}
/**
* Dismiss the recent activities dialog.
*/
@Override
public void onStop() {
super.onStop();
// dump extra memory we're hanging on to
for (View b : mButtons) {
setButtonAppearance(b, null, null);
b.setTag(null);
}
if (sStatusBar != null) {
sStatusBar.disable(StatusBarManager.DISABLE_NONE);
}
// stop receiving broadcasts
getContext().unregisterReceiver(mBroadcastReceiver);
}
/**
* Reload the 6 buttons with recent activities
*/
private void reloadButtons() {
final Context context = getContext();
final PackageManager pm = context.getPackageManager();
final ActivityManager am = (ActivityManager)
context.getSystemService(Context.ACTIVITY_SERVICE);
final List<ActivityManager.RecentTaskInfo> recentTasks =
am.getRecentTasks(MAX_RECENT_TASKS, 0);
ResolveInfo homeInfo = pm.resolveActivity(
new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME),
0);
// Performance note: Our android performance guide says to prefer Iterator when
// using a List class, but because we know that getRecentTasks() always returns
// an ArrayList<>, we'll use a simple index instead.
int button = 0;
int numTasks = recentTasks.size();
for (int i = 0; i < numTasks && (button < NUM_BUTTONS); ++i) {
final ActivityManager.RecentTaskInfo info = recentTasks.get(i);
// for debug purposes only, disallow first result to create empty lists
if (DBG_FORCE_EMPTY_LIST && (i == 0)) continue;
Intent intent = new Intent(info.baseIntent);
if (info.origActivity != null) {
intent.setComponent(info.origActivity);
}
// Skip the current home activity.
if (homeInfo != null) {
if (homeInfo.activityInfo.packageName.equals(
intent.getComponent().getPackageName())
&& homeInfo.activityInfo.name.equals(
intent.getComponent().getClassName())) {
continue;
}
}
intent.setFlags((intent.getFlags()&~Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
| Intent.FLAG_ACTIVITY_NEW_TASK);
final ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
if (resolveInfo != null) {
final ActivityInfo activityInfo = resolveInfo.activityInfo;
final String title = activityInfo.loadLabel(pm).toString();
final Drawable icon = activityInfo.loadIcon(pm);
if (title != null && title.length() > 0 && icon != null) {
final View b = mButtons[button];
setButtonAppearance(b, title, icon);
b.setTag(intent);
b.setVisibility(View.VISIBLE);
b.setPressed(false);
b.clearFocus();
++button;
}
}
}
// handle the case of "no icons to show"
mNoAppsText.setVisibility((button == 0) ? View.VISIBLE : View.GONE);
// hide the rest
for ( ; button < NUM_BUTTONS; ++button) {
mButtons[button].setVisibility(View.GONE);
}
}
/**
* Adjust appearance of each icon-button
*/
private void setButtonAppearance(View theButton, final String theTitle, final Drawable icon) {
TextView tv = (TextView) theButton.findViewById(com.android.internal.R.id.label);
tv.setText(theTitle);
ImageView iv = (ImageView) theButton.findViewById(com.android.internal.R.id.icon);
iv.setImageDrawable(icon);
}
/**
* This is the listener for the ACTION_CLOSE_SYSTEM_DIALOGS intent. It's an indication that
* we should close ourselves immediately, in order to allow a higher-priority UI to take over
* (e.g. phone call received).
*
* TODO: This is a really heavyweight solution for something that should be so simple.
* For example, we already have a handler, in our superclass, why aren't we sharing that?
* I think we need to investigate simplifying this entire methodology, or perhaps boosting
* it up into the Dialog class.
*/
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
String reason = intent.getStringExtra(PhoneWindowManager.SYSTEM_DIALOG_REASON_KEY);
if (! PhoneWindowManager.SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {
dismiss();
}
}
}
};
}

View File

@@ -1,120 +0,0 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyCharacterMap;
import java.net.URISyntaxException;
/**
* Manages quick launch shortcuts by:
* <li> Keeping the local copy in sync with the database (this is an observer)
* <li> Returning a shortcut-matching intent to clients
*/
class ShortcutManager extends ContentObserver {
private static final String TAG = "ShortcutManager";
private static final int COLUMN_SHORTCUT = 0;
private static final int COLUMN_INTENT = 1;
private static final String[] sProjection = new String[] {
Settings.Bookmarks.SHORTCUT, Settings.Bookmarks.INTENT
};
private Context mContext;
private Cursor mCursor;
/** Map of a shortcut to its intent. */
private SparseArray<Intent> mShortcutIntents;
public ShortcutManager(Context context, Handler handler) {
super(handler);
mContext = context;
mShortcutIntents = new SparseArray<Intent>();
}
/** Observes the provider of shortcut+intents */
public void observe() {
mCursor = mContext.getContentResolver().query(
Settings.Bookmarks.CONTENT_URI, sProjection, null, null, null);
mCursor.registerContentObserver(this);
updateShortcuts();
}
@Override
public void onChange(boolean selfChange) {
updateShortcuts();
}
private void updateShortcuts() {
Cursor c = mCursor;
if (!c.requery()) {
Log.e(TAG, "ShortcutObserver could not re-query shortcuts.");
return;
}
mShortcutIntents.clear();
while (c.moveToNext()) {
int shortcut = c.getInt(COLUMN_SHORTCUT);
if (shortcut == 0) continue;
String intentURI = c.getString(COLUMN_INTENT);
Intent intent = null;
try {
intent = Intent.getIntent(intentURI);
} catch (URISyntaxException e) {
Log.w(TAG, "Intent URI for shortcut invalid.", e);
}
if (intent == null) continue;
mShortcutIntents.put(shortcut, intent);
}
}
/**
* Gets the shortcut intent for a given keycode+modifier. Make sure you
* strip whatever modifier is used for invoking shortcuts (for example,
* if 'Sym+A' should invoke a shortcut on 'A', you should strip the
* 'Sym' bit from the modifiers before calling this method.
* <p>
* This will first try an exact match (with modifiers), and then try a
* match without modifiers (primary character on a key).
*
* @param keyCode The keycode of the key pushed.
* @param modifiers The modifiers without any that are used for chording
* to invoke a shortcut.
* @return The intent that matches the shortcut, or null if not found.
*/
public Intent getIntent(int keyCode, int modifiers) {
KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
// First try the exact keycode (with modifiers)
int shortcut = kcm.get(keyCode, modifiers);
Intent intent = shortcut != 0 ? mShortcutIntents.get(shortcut) : null;
if (intent != null) return intent;
// Next try the keycode without modifiers (the primary character on that key)
shortcut = Character.toLowerCase(kcm.get(keyCode, 0));
return shortcut != 0 ? mShortcutIntents.get(shortcut) : null;
}
}

View File

@@ -1,138 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.app.ProgressDialog;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.RemoteException;
import android.os.Power;
import android.os.ServiceManager;
import android.os.SystemClock;
import com.android.internal.telephony.ITelephony;
import android.util.Log;
import android.view.WindowManager;
final class ShutdownThread extends Thread {
// constants
private static final String TAG = "ShutdownThread";
private static final int MAX_NUM_PHONE_STATE_READS = 16;
private static final int PHONE_STATE_POLL_SLEEP_MSEC = 500;
private static final ITelephony sPhone =
ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
// state tracking
private static Object sIsStartedGuard = new Object();
private static boolean sIsStarted = false;
// static instance of this thread
private static final ShutdownThread sInstance = new ShutdownThread();
private ShutdownThread() {
}
/**
* request a shutdown.
*
* @param context Context used to display the shutdown progress dialog.
*/
public static void shutdownAfterDisablingRadio(final Context context, boolean confirm){
// ensure that only one thread is trying to power down.
// any additional calls are just returned
synchronized (sIsStartedGuard){
if (sIsStarted) {
Log.d(TAG, "Request to shutdown already running, returning.");
return;
}
}
Log.d(TAG, "Notifying thread to start radio shutdown");
if (confirm) {
final AlertDialog dialog = new AlertDialog.Builder(context)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(com.android.internal.R.string.power_off)
.setMessage(com.android.internal.R.string.shutdown_confirm)
.setPositiveButton(com.android.internal.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
beginShutdownSequence(context);
}
})
.setNegativeButton(com.android.internal.R.string.no, null)
.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
dialog.show();
} else {
beginShutdownSequence(context);
}
}
private static void beginShutdownSequence(Context context) {
synchronized (sIsStartedGuard) {
sIsStarted = true;
}
// throw up an indeterminate system dialog to indicate radio is
// shutting down.
ProgressDialog pd = new ProgressDialog(context);
pd.setTitle(context.getText(com.android.internal.R.string.power_off));
pd.setMessage(context.getText(com.android.internal.R.string.shutdown_progress));
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
pd.show();
// start the thread that initiates shutdown
sInstance.start();
}
/**
* Makes sure we handle the shutdown gracefully.
* Shuts off power regardless of radio state if the alloted time has passed.
*/
public void run() {
//shutdown the phone radio if possible.
if (sPhone != null) {
try {
//shutdown radio
sPhone.setRadio(false);
for (int i = 0; i < MAX_NUM_PHONE_STATE_READS; i++){
// poll radio up to 64 times, with a 0.5 sec delay between each call,
// totaling 32 sec.
if (!sPhone.isRadioOn()) {
Log.d(TAG, "Radio shutdown complete.");
break;
}
SystemClock.sleep(PHONE_STATE_POLL_SLEEP_MSEC);
}
} catch (RemoteException ex) {
Log.e(TAG, "RemoteException caught from failed radio shutdown.", ex);
}
}
//shutdown power
Log.d(TAG, "Shutting down power.");
Power.shutdown();
}
}

View File

@@ -1,366 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.RemoteException;
import android.os.ServiceManager;
import com.android.internal.telephony.ITelephony;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.internal.R;
/**
* Displays a dialer like interface to unlock the SIM PIN.
*/
public class SimUnlockScreen extends LinearLayout implements KeyguardScreen, View.OnClickListener,
KeyguardUpdateMonitor.ConfigurationChangeCallback {
private static final int DIGIT_PRESS_WAKE_MILLIS = 5000;
private final KeyguardUpdateMonitor mUpdateMonitor;
private final KeyguardScreenCallback mCallback;
private final boolean mCreatedWithKeyboardOpen;
private TextView mHeaderText;
private EditText mPinText;
private TextView mOkButton;
private TextView mEmergencyCallButton;
private View mBackSpaceButton;
private final int[] mEnteredPin = {0, 0, 0, 0, 0, 0, 0, 0};
private int mEnteredDigits = 0;
private ProgressDialog mSimUnlockProgressDialog = null;
private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
public SimUnlockScreen(Context context, KeyguardUpdateMonitor updateMonitor,
KeyguardScreenCallback callback) {
super(context);
mUpdateMonitor = updateMonitor;
mCallback = callback;
mCreatedWithKeyboardOpen = mUpdateMonitor.isKeyboardOpen();
if (mCreatedWithKeyboardOpen) {
LayoutInflater.from(context).inflate(R.layout.keyguard_screen_sim_pin_landscape, this, true);
} else {
LayoutInflater.from(context).inflate(R.layout.keyguard_screen_sim_pin_portrait, this, true);
new TouchInput();
}
mHeaderText = (TextView) findViewById(R.id.headerText);
mPinText = (EditText) findViewById(R.id.pinDisplay);
mBackSpaceButton = findViewById(R.id.backspace);
mBackSpaceButton.setOnClickListener(this);
mEmergencyCallButton = (TextView) findViewById(R.id.emergencyCall);
mOkButton = (TextView) findViewById(R.id.ok);
mHeaderText.setText(R.string.keyguard_password_enter_pin_code);
mPinText.setFocusable(false);
mEmergencyCallButton.setOnClickListener(this);
mOkButton.setOnClickListener(this);
mUpdateMonitor.registerConfigurationChangeCallback(this);
setFocusableInTouchMode(true);
}
/** {@inheritDoc} */
public boolean needsInput() {
return true;
}
/** {@inheritDoc} */
public void onPause() {
}
/** {@inheritDoc} */
public void onResume() {
// start fresh
mHeaderText.setText(R.string.keyguard_password_enter_pin_code);
// make sure that the number of entered digits is consistent when we
// erase the SIM unlock code, including orientation changes.
mPinText.setText("");
mEnteredDigits = 0;
}
/** {@inheritDoc} */
public void cleanUp() {
// hide the dialog.
if (mSimUnlockProgressDialog != null) {
mSimUnlockProgressDialog.hide();
}
mUpdateMonitor.removeCallback(this);
}
/**
* Since the IPC can block, we want to run the request in a separate thread
* with a callback.
*/
private abstract class CheckSimPin extends Thread {
private final String mPin;
protected CheckSimPin(String pin) {
mPin = pin;
}
abstract void onSimLockChangedResponse(boolean success);
@Override
public void run() {
try {
final boolean result = ITelephony.Stub.asInterface(ServiceManager
.checkService("phone")).supplyPin(mPin);
post(new Runnable() {
public void run() {
onSimLockChangedResponse(result);
}
});
} catch (RemoteException e) {
post(new Runnable() {
public void run() {
onSimLockChangedResponse(false);
}
});
}
}
}
public void onClick(View v) {
if (v == mBackSpaceButton) {
final Editable digits = mPinText.getText();
final int len = digits.length();
if (len > 0) {
digits.delete(len-1, len);
mEnteredDigits--;
}
mCallback.pokeWakelock();
} else if (v == mEmergencyCallButton) {
mCallback.takeEmergencyCallAction();
} else if (v == mOkButton) {
checkPin();
}
}
private Dialog getSimUnlockProgressDialog() {
if (mSimUnlockProgressDialog == null) {
mSimUnlockProgressDialog = new ProgressDialog(mContext);
mSimUnlockProgressDialog.setMessage(
mContext.getString(R.string.lockscreen_sim_unlock_progress_dialog_message));
mSimUnlockProgressDialog.setIndeterminate(true);
mSimUnlockProgressDialog.setCancelable(false);
mSimUnlockProgressDialog.getWindow().setType(
WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
mSimUnlockProgressDialog.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
}
return mSimUnlockProgressDialog;
}
private void checkPin() {
// make sure that the pin is at least 4 digits long.
if (mEnteredDigits < 4) {
// otherwise, display a message to the user, and don't submit.
mHeaderText.setText(R.string.invalidPin);
mPinText.setText("");
mEnteredDigits = 0;
mCallback.pokeWakelock();
return;
}
getSimUnlockProgressDialog().show();
new CheckSimPin(mPinText.getText().toString()) {
void onSimLockChangedResponse(boolean success) {
if (mSimUnlockProgressDialog != null) {
mSimUnlockProgressDialog.hide();
}
if (success) {
// before closing the keyguard, report back that
// the sim is unlocked so it knows right away
mUpdateMonitor.reportSimPinUnlocked();
mCallback.goToUnlockScreen();
} else {
mHeaderText.setText(R.string.keyguard_password_wrong_pin_code);
mPinText.setText("");
mEnteredDigits = 0;
mCallback.pokeWakelock();
}
}
}.start();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
mCallback.goToLockScreen();
return true;
}
final char match = event.getMatch(DIGITS);
if (match != 0) {
reportDigit(match - '0');
return true;
}
if (keyCode == KeyEvent.KEYCODE_DEL) {
if (mEnteredDigits > 0) {
mPinText.onKeyDown(keyCode, event);
mEnteredDigits--;
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_ENTER) {
checkPin();
return true;
}
return false;
}
private void reportDigit(int digit) {
if (mEnteredDigits == 0) {
mPinText.setText("");
}
if (mEnteredDigits == 8) {
return;
}
mPinText.append(Integer.toString(digit));
mEnteredPin[mEnteredDigits++] = digit;
}
public void onOrientationChange(boolean inPortrait) {}
public void onKeyboardChange(boolean isKeyboardOpen) {
if (isKeyboardOpen != mCreatedWithKeyboardOpen) {
mCallback.recreateMe();
}
}
/**
* Helper class to handle input from touch dialer. Only relevant when
* the keyboard is shut.
*/
private class TouchInput implements View.OnClickListener {
private TextView mZero;
private TextView mOne;
private TextView mTwo;
private TextView mThree;
private TextView mFour;
private TextView mFive;
private TextView mSix;
private TextView mSeven;
private TextView mEight;
private TextView mNine;
private TextView mCancelButton;
private TouchInput() {
mZero = (TextView) findViewById(R.id.zero);
mOne = (TextView) findViewById(R.id.one);
mTwo = (TextView) findViewById(R.id.two);
mThree = (TextView) findViewById(R.id.three);
mFour = (TextView) findViewById(R.id.four);
mFive = (TextView) findViewById(R.id.five);
mSix = (TextView) findViewById(R.id.six);
mSeven = (TextView) findViewById(R.id.seven);
mEight = (TextView) findViewById(R.id.eight);
mNine = (TextView) findViewById(R.id.nine);
mCancelButton = (TextView) findViewById(R.id.cancel);
mZero.setText("0");
mOne.setText("1");
mTwo.setText("2");
mThree.setText("3");
mFour.setText("4");
mFive.setText("5");
mSix.setText("6");
mSeven.setText("7");
mEight.setText("8");
mNine.setText("9");
mZero.setOnClickListener(this);
mOne.setOnClickListener(this);
mTwo.setOnClickListener(this);
mThree.setOnClickListener(this);
mFour.setOnClickListener(this);
mFive.setOnClickListener(this);
mSix.setOnClickListener(this);
mSeven.setOnClickListener(this);
mEight.setOnClickListener(this);
mNine.setOnClickListener(this);
mCancelButton.setOnClickListener(this);
}
public void onClick(View v) {
if (v == mCancelButton) {
mCallback.goToLockScreen();
return;
}
final int digit = checkDigit(v);
if (digit >= 0) {
mCallback.pokeWakelock(DIGIT_PRESS_WAKE_MILLIS);
reportDigit(digit);
}
}
private int checkDigit(View v) {
int digit = -1;
if (v == mZero) {
digit = 0;
} else if (v == mOne) {
digit = 1;
} else if (v == mTwo) {
digit = 2;
} else if (v == mThree) {
digit = 3;
} else if (v == mFour) {
digit = 4;
} else if (v == mFive) {
digit = 5;
} else if (v == mSix) {
digit = 6;
} else if (v == mSeven) {
digit = 7;
} else if (v == mEight) {
digit = 8;
} else if (v == mNine) {
digit = 9;
}
return digit;
}
}
}

View File

@@ -1,341 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.internal.R;
import com.android.internal.widget.LinearLayoutWithDefaultTouchRecepient;
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.LockPatternView;
import java.util.List;
/**
* This is the screen that shows the 9 circle unlock widget and instructs
* the user how to unlock their device, or make an emergency call.
*/
class UnlockScreen extends LinearLayoutWithDefaultTouchRecepient
implements KeyguardScreen, KeyguardUpdateMonitor.ConfigurationChangeCallback {
private static final String TAG = "UnlockScreen";
// how long before we clear the wrong pattern
private static final int PATTERN_CLEAR_TIMEOUT_MS = 2000;
// how long we stay awake once the user is ready to enter a pattern
private static final int UNLOCK_PATTERN_WAKE_INTERVAL_MS = 7000;
private int mFailedPatternAttemptsSinceLastTimeout = 0;
private int mTotalFailedPatternAttempts = 0;
private CountDownTimer mCountdownTimer = null;
private final LockPatternUtils mLockPatternUtils;
private final KeyguardUpdateMonitor mUpdateMonitor;
private final KeyguardScreenCallback mCallback;
private boolean mCreatedInPortrait;
private ImageView mUnlockIcon;
private TextView mUnlockHeader;
private LockPatternView mLockPatternView;
private ViewGroup mFooterNormal;
private ViewGroup mFooterForgotPattern;
/**
* Keeps track of the last time we poked the wake lock during dispatching
* of the touch event, initalized to something gauranteed to make us
* poke it when the user starts drawing the pattern.
* @see #dispatchTouchEvent(android.view.MotionEvent)
*/
private long mLastPokeTime = -UNLOCK_PATTERN_WAKE_INTERVAL_MS;
/**
* Useful for clearing out the wrong pattern after a delay
*/
private Runnable mCancelPatternRunnable = new Runnable() {
public void run() {
mLockPatternView.clearPattern();
}
};
private Button mForgotPatternButton;
private ServiceConnection mServiceConnection;
enum FooterMode {
Normal,
ForgotLockPattern,
VerifyUnlocked
}
private void updateFooter(FooterMode mode) {
switch (mode) {
case Normal:
mFooterNormal.setVisibility(View.VISIBLE);
mFooterForgotPattern.setVisibility(View.GONE);
break;
case ForgotLockPattern:
mFooterNormal.setVisibility(View.GONE);
mFooterForgotPattern.setVisibility(View.VISIBLE);
break;
case VerifyUnlocked:
mFooterNormal.setVisibility(View.GONE);
mFooterForgotPattern.setVisibility(View.GONE);
}
}
/**
* @param context The context.
* @param lockPatternUtils Used to lookup lock pattern settings.
* @param updateMonitor Used to lookup state affecting keyguard.
* @param callback Used to notify the manager when we're done, etc.
* @param totalFailedAttempts The current number of failed attempts.
*/
UnlockScreen(Context context,
LockPatternUtils lockPatternUtils,
KeyguardUpdateMonitor updateMonitor,
KeyguardScreenCallback callback,
int totalFailedAttempts) {
super(context);
mLockPatternUtils = lockPatternUtils;
mUpdateMonitor = updateMonitor;
mCallback = callback;
mTotalFailedPatternAttempts = totalFailedAttempts;
mFailedPatternAttemptsSinceLastTimeout = totalFailedAttempts % LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT;
if (mUpdateMonitor.isInPortrait()) {
LayoutInflater.from(context).inflate(R.layout.keyguard_screen_unlock_portrait, this, true);
} else {
LayoutInflater.from(context).inflate(R.layout.keyguard_screen_unlock_landscape, this, true);
}
mUnlockIcon = (ImageView) findViewById(R.id.unlockLockIcon);
mLockPatternView = (LockPatternView) findViewById(R.id.lockPattern);
mUnlockHeader = (TextView) findViewById(R.id.headerText);
mUnlockHeader.setText(R.string.lockscreen_pattern_instructions);
mFooterNormal = (ViewGroup) findViewById(R.id.footerNormal);
mFooterForgotPattern = (ViewGroup) findViewById(R.id.footerForgotPattern);
// emergency call buttons
final OnClickListener emergencyClick = new OnClickListener() {
public void onClick(View v) {
mCallback.takeEmergencyCallAction();
}
};
Button emergencyAlone = (Button) findViewById(R.id.emergencyCallAlone);
emergencyAlone.setFocusable(false); // touch only!
emergencyAlone.setOnClickListener(emergencyClick);
Button emergencyTogether = (Button) findViewById(R.id.emergencyCallTogether);
emergencyTogether.setFocusable(false);
emergencyTogether.setOnClickListener(emergencyClick);
mForgotPatternButton = (Button) findViewById(R.id.forgotPattern);
mForgotPatternButton.setText(R.string.lockscreen_forgot_pattern_button_text);
mForgotPatternButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mLockPatternUtils.setPermanentlyLocked(true);
mCallback.goToUnlockScreen();
}
});
// make it so unhandled touch events within the unlock screen go to the
// lock pattern view.
setDefaultTouchRecepient(mLockPatternView);
mLockPatternView.setSaveEnabled(false);
mLockPatternView.setFocusable(false);
mLockPatternView.setOnPatternListener(new UnlockPatternListener());
// stealth mode will be the same for the life of this screen
mLockPatternView.setInStealthMode(!mLockPatternUtils.isVisiblePatternEnabled());
// vibrate mode will be the same for the life of this screen
mLockPatternView.setTactileFeedbackEnabled(mLockPatternUtils.isTactileFeedbackEnabled());
// assume normal footer mode for now
updateFooter(FooterMode.Normal);
mCreatedInPortrait = updateMonitor.isInPortrait();
updateMonitor.registerConfigurationChangeCallback(this);
setFocusableInTouchMode(true);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
mCallback.goToLockScreen();
return true;
}
return false;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// as long as the user is entering a pattern (i.e sending a touch
// event that was handled by this screen), keep poking the
// wake lock so that the screen will stay on.
final boolean result = super.dispatchTouchEvent(ev);
if (result &&
((SystemClock.elapsedRealtime() - mLastPokeTime)
> (UNLOCK_PATTERN_WAKE_INTERVAL_MS - 100))) {
mLastPokeTime = SystemClock.elapsedRealtime();
mCallback.pokeWakelock(UNLOCK_PATTERN_WAKE_INTERVAL_MS);
}
return result;
}
/** {@inheritDoc} */
public void onOrientationChange(boolean inPortrait) {
if (inPortrait != mCreatedInPortrait) {
mCallback.recreateMe();
}
}
/** {@inheritDoc} */
public void onKeyboardChange(boolean isKeyboardOpen) {}
/** {@inheritDoc} */
public boolean needsInput() {
return false;
}
/** {@inheritDoc} */
public void onPause() {
if (mCountdownTimer != null) {
mCountdownTimer.cancel();
mCountdownTimer = null;
}
}
/** {@inheritDoc} */
public void onResume() {
// reset header
mUnlockHeader.setText(R.string.lockscreen_pattern_instructions);
mUnlockIcon.setVisibility(View.VISIBLE);
// reset lock pattern
mLockPatternView.enableInput();
mLockPatternView.setEnabled(true);
mLockPatternView.clearPattern();
// show "forgot pattern?" button if we have an alternate authentication method
mForgotPatternButton.setVisibility(mCallback.doesFallbackUnlockScreenExist()
? View.VISIBLE : View.INVISIBLE);
// if the user is currently locked out, enforce it.
long deadline = mLockPatternUtils.getLockoutAttemptDeadline();
if (deadline != 0) {
handleAttemptLockout(deadline);
}
// the footer depends on how many total attempts the user has failed
if (mCallback.isVerifyUnlockOnly()) {
updateFooter(FooterMode.VerifyUnlocked);
} else if (mTotalFailedPatternAttempts < LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
updateFooter(FooterMode.Normal);
} else {
updateFooter(FooterMode.ForgotLockPattern);
}
}
/** {@inheritDoc} */
public void cleanUp() {
mUpdateMonitor.removeCallback(this);
}
private class UnlockPatternListener
implements LockPatternView.OnPatternListener {
public void onPatternStart() {
mLockPatternView.removeCallbacks(mCancelPatternRunnable);
}
public void onPatternCleared() {
}
public void onPatternDetected(List<LockPatternView.Cell> pattern) {
if (mLockPatternUtils.checkPattern(pattern)) {
mLockPatternView
.setDisplayMode(LockPatternView.DisplayMode.Correct);
mUnlockIcon.setVisibility(View.GONE);
mUnlockHeader.setText(R.string.lockscreen_pattern_correct);
mCallback.keyguardDone(true);
} else {
mCallback.pokeWakelock(UNLOCK_PATTERN_WAKE_INTERVAL_MS);
mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
if (pattern.size() >= LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {
mTotalFailedPatternAttempts++;
mFailedPatternAttemptsSinceLastTimeout++;
mCallback.reportFailedPatternAttempt();
}
if (mFailedPatternAttemptsSinceLastTimeout >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
long deadline = mLockPatternUtils.setLockoutAttemptDeadline();
handleAttemptLockout(deadline);
return;
}
mUnlockIcon.setVisibility(View.VISIBLE);
mUnlockHeader.setText(R.string.lockscreen_pattern_wrong);
mLockPatternView.postDelayed(
mCancelPatternRunnable,
PATTERN_CLEAR_TIMEOUT_MS);
}
}
}
private void handleAttemptLockout(long elapsedRealtimeDeadline) {
mLockPatternView.clearPattern();
mLockPatternView.setEnabled(false);
long elapsedRealtime = SystemClock.elapsedRealtime();
mCountdownTimer = new CountDownTimer(elapsedRealtimeDeadline - elapsedRealtime, 1000) {
@Override
public void onTick(long millisUntilFinished) {
int secondsRemaining = (int) (millisUntilFinished / 1000);
mUnlockHeader.setText(getContext().getString(
R.string.lockscreen_too_many_failed_attempts_countdown,
secondsRemaining));
}
@Override
public void onFinish() {
mLockPatternView.setEnabled(true);
mUnlockHeader.setText(R.string.lockscreen_pattern_instructions);
mUnlockIcon.setVisibility(View.VISIBLE);
mFailedPatternAttemptsSinceLastTimeout = 0;
updateFooter(FooterMode.ForgotLockPattern);
}
}.start();
}
}

View File

@@ -1,5 +0,0 @@
<body>
{@hide}
</body>