这篇博客只是一个demo,记录一种思想,采用windowmanager来屏蔽home键,因为采用activity貌似行不通,后来了解了windowmanager之后才明白,记录一下。
//这里只是一个按钮,点击启动一个service
public class MainActivity extends Activity {
private Button btn_lockscrren;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_lockscrren = (Button) findViewById(R.id.btn_lockscrren);
btn_lockscrren.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent mIntent = new Intent(MainActivity.this,LockScreenService.class);
startService(mIntent);
}
});
}
}
关键代码
public class LockScreenService extends Service {
private View lockScreenView;
private Button btn_unlock;
private WindowManager mWindowManager;
private WindowManager.LayoutParams lp;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressLint("InlinedApi")
@Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
lp = new WindowManager.LayoutParams();
//设置类型
lp.type = WindowManager.LayoutParams.TYPE_PHONE;
//设置lp为竖屏显示
lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
//解除锁屏,如果想查看flags里面的常量是什么意思请点击右边博客链接详细说明了,http://blog.csdn.net/liuhaomatou/article/details/22899925/
lp.flags |= LayoutParams.FLAG_DISMISS_KEYGUARD;
lp.flags |= LayoutParams.FLAG_SHOW_WHEN_LOCKED;
//设置铺满全屏
lp.flags |= LayoutParams.FLAG_FULLSCREEN;
//窗口占满整个屏幕,忽略周围的装饰边框
lp.flags |= LayoutParams.FLAG_LAYOUT_IN_SCREEN;
if(VERSION.SDK_INT >= VERSION_CODES.KITKAT){
lp.flags |= LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
lp.flags |= LayoutParams.FLAG_TRANSLUCENT_STATUS;
}
//设置大小
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
//设置开始位置
lp.x = 0;
lp.y = 0;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(lockScreenView == null){
lockScreenView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_inflater, null);
btn_unlock = (Button) lockScreenView.findViewById(R.id.btn_unlock);
btn_unlock.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//点击解锁
mWindowManager.removeViewImmediate(lockScreenView);
}
});
}
mWindowManager.addView(lockScreenView, lp);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
if(mWindowManager != null){
mWindowManager = null;
}
super.onDestroy();
}
}
最后附上下载链接
http://download.csdn.net/my