在智能管家App项目的开发过程中有一个这样的功能,在服务中写一个窗口,之后这个窗口需要通过Back键关闭,但是由于窗口是在服务Service中的,显然我们无法像在Activity中通过回调onBackPressed()方法来关闭窗口,因此在网上查阅了事件分发的相关资料和刘某人程序员的博客后,总算学习到了如何解决该问题。
http://blog.csdn.net/qq_26787115/article/details/52260393
首先我们完成这个在服务中弹出Window的服务类
package com.liuguilin.keyevevtsample;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class WindowService extends Service implements View.OnClickListener {
//窗口管理器
private WindowManager wm;
//view
private View mView;
//布局参数
private WindowManager.LayoutParams layoutParams;
//取消window
private Button btnCloseWindow;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
initWindow();
}
/**
* 初始化Window
*/
private void initWindow() {
//窗口管理器
wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
//布局参数
layoutParams = new WindowManager.LayoutParams();
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.flags =
//WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | 不能触摸
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
//格式
layoutParams.format = PixelFormat.TRANSLUCENT;
//类型
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
mView = View.inflate(getApplicationContext(), R.la