我知道这个问题被问了很多次,但我发现没有一个解决方案是有效的。
我试过下面给出的代码…
protected void onPause() {
super.onPause();
Intent intent = new Intent(this,LockActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT |Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
它的作用是当Android主屏幕启动时,将当前的活动重新放在前面,但是当主屏幕启动时,将活动重新启动到前面几乎需要3-4秒钟。
我已经使用一些锁屏应用程序,甚至在家庭按钮被点击时甚至不启动主屏幕。我想要实现这样的东西。
我也使用了onUserLeavesHint方法,onKeyDown方法和onKeyDispatch方法,但没有一个为我工作。
请不要回答或评论,因为无法在Android中禁用主页按钮。对于这样的答案或意见,我建议您通过PlayStore上的一些Lock Screen应用程序。另外我发现一个工作的应用程序在github源代码。这是在我的手机上工作,该应用程序使用disableKeyguard,但是当我在我的应用程序中执行相同操作不起作用(disableKeyguard已被弃用,但我使用@supress警告(“deprecation”))。
//Copy this class
public class HomeKeyLocker {
private OverlayDialog mOverlayDialog;
public void lock(Activity activity) {
if (mOverlayDialog == null) {
mOverlayDialog = new OverlayDialog(activity);
mOverlayDialog.show();
}
}
public void unlock() {
if (mOverlayDialog != null) {
mOverlayDialog.dismiss();
mOverlayDialog = null;
}
}
private static class OverlayDialog extends AlertDialog {
public OverlayDialog(Activity activity) {
super(activity, R.style.OverlayDialog);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
params.dimAmount = 0.0F; // transparent
params.width = 0;
params.height = 0;
params.gravity = Gravity.BOTTOM;
getWindow().setAttributes(params);
getWindow().setFlags( WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, 0xffffff);
setOwnerActivity(activity);
setCancelable(false);
}
public final boolean dispatchTouchEvent(MotionEvent motionevent) {
return true;
}
protected final void onCreate(Bundle bundle) {
super.onCreate(bundle);
FrameLayout framelayout = new FrameLayout(getContext());
framelayout.setBackgroundColor(0);
setContentView(framelayout);
}
}
}
//Paste this in your activity
mHomeKeyLocker = new HomeKeyLocker();
mHomeKeyLocker.lock(this);