本人使用的是这段代码 http://www.2cto.com/kf/201210/159724.html
使用过程中由于有些许粗心, 纠结了差不多一天,只有两异常:
1.view not attach to the window manager
2.timertask is scheduled already
相关代码:
shakeEventController.setOnShakeListener(new OnShakeListener() { @Override public void OnShake() { //此事件中进行截图 //先隐藏悬浮窗 Log.i("摇一摇context", btnScreenShot.getContext().toString()); wm.removeViewImmediate(btnScreenShot); isAdded = false; //延迟1000MS+设置延迟 截图 if(timer!=null){ timer.cancel(); } timer = new Timer(); if(screenShotTask!=null){ screenShotTask.cancel(); } screenShotTask = new ScreenShotTask(); int delay = 1000 + (shotDelay * 1000); timer.schedule(screenShotTask, delay); } });
下面分析原因:
由于我在做一个截图项目,有一个悬浮按钮,用来截图,当我用摇一摇截图的时候,悬浮按钮需要从windowManager中remove,第一次remove倒是很正常,但是第二次摇的时候,就出现了异常1。这个相当诡异,后来不经意间发现了,在第二次摇一摇的时候,调用了两次remove,然后真想大白。
扫描二维码关注公众号,回复:
709643 查看本文章
我的悬浮窗实在一个intentservice中创建的,因此每次onhandleintent的时候就会调用上面那段代码,因此,第一次摇一摇很正常,在第二次摇的时候,shakeEventController中已经存在了一个已注册的ACCELEROMETER的sensor,然后在此调用这段代码,就有两个sensor在监听onshake事件,因此在第二个onshake事件处理的时候,btnScreenShot已经从windowmanager中remove掉了,所以抛出异常:view not attach to the window manager。
第二个异常,同理,这个事件处理了两次,而且几乎是同时的,一个timertask还没完的时候,另一个又schedule,肯定抛出异常:timertask is scheduled already