另一种开发 LockScreen 应用的方法是使用 Views,让我解释一下。
首先,您可以通过禁用KEYGUARD:在某些设备中“禁用”系统锁定屏幕:
((KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE)).newKeyguardLock("IN").disableKeyguard();
你应该把这行代码放在你的Service中。
之后,您可以在每次屏幕关闭时启动一个活动:
public class AutoStart extends BroadcastReceiver {
public void onReceive(Context arg0, Intent arg1) {
if(arg1.getAction().equals("android.intent.action.SCREEN_OFF")) {
Intent localIntent = new Intent(arg0, LockScreen.class);
localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
localIntent.addFlags(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
arg0.startActivity(localIntent);
}
}
}
如果您阅读了WindowManager.LayoutParams.TYPE_SYSTEM_ERROR 的文档,它会说明这是一种内部系统错误窗口,它会出现在所有可能出现的位置之上。在多用户系统中,仅在拥有用户的窗口上显示。
所以现在你有一个最重要的活动,但按下HOME 按钮将退出活动。
视图在这里出现。您可以从布局资源中扩充视图并将其添加到WindowManager 作为TYPE_SYSTEM_ERROR,因此将在所有内容之上。而且由于您可以控制何时删除此视图,因此最好的位置是在您的Activity 中的onDestroy,因为按下HOME 按钮只会暂停您的活动,而视图仍将可见。
public WindowManager winManager;
public RelativeLayout wrapperView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
PixelFormat.TRANSLUCENT);
this.winManager = ((WindowManager)getApplicationContext().getSystemService(WINDOW_SERVICE));
this.wrapperView = new RelativeLayout(getBaseContext());
getWindow().setAttributes(localLayoutParams);
View.inflate(this, R.layout.lock_screen, this.wrapperView);
this.winManager.addView(this.wrapperView, localLayoutParams);
}
public void onDestroy()
{
this.winManager.removeView(this.wrapperView);
this.wrapperView.removeAllViews();
super.onDestroy();
}
为了避免显示通知栏,我添加了标志FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL | FLAG_LAYOUT_IN_SCREEN 以消耗所有指针事件。
不要忘记将这两行添加到您的清单中:
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
从这里你只需要添加你的锁屏应用程序的逻辑来让用户使用他的智能手机:)