静态广播重复创建对象

来源:互联网 发布:数据库中索引是什么 编辑:程序博客网 时间:2024/05/21 15:01

项目有一个监听来电并做一个弹窗的需求。

于是乎首先想到的是静态注册,然而在运行过程中发现,只能让弹窗显示,移除弹窗的时候缺没有移除。。。

<receiver android:name=".PhoneStateReceiver">      <intent-filter>          <action android:name="android.intent.action.PHONE_STATE</span>    </intent-filter>  </receiver>  

下面代码是根据网上的代码改的,项目代码就不贴了,都懂得。。。

http://www.iteye.com/topic/1118711 这是传送门

WindowManager wm;TextView tv;public void onReceive(Context context,Intent intent){    String action = intent.getAction();    if(action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)){     TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);          int state = telephony.getCallState();         if(state == TelephonyManager.CALL_STATE_RINGING){              wm = (WindowManager)context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);                WindowManager.LayoutParams params = new WindowManager.LayoutParams();                params.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;                params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;               params.width = WindowManager.LayoutParams.WRAP_CONTENT;                params.height = WindowManager.LayoutParams.WRAP_CONTENT;                params.format = PixelFormat.RGBA_8888;              tv = new TextView(context);               tv.setText("来电号码:" + incomingNumber);              wm.addView(tv, params);                                }else if(state == TelephonyManager.CALL_STATE_IDLE){              if(wm != null){                  wm.removeView(tv);              }          }  }
跟踪代码可以发现在wm.removeView的时候 wm和tv都是空的。

因为从来电到接听时间较短,所以不会是资源被回收掉了。

多次调试发现,每次调用广播接收器的时候,都会new BroadReceiver对象。。。。。

自然在广播接受到CALL_STATE_IDLED的时候,wm和tv实际上是个未赋值的null对象

无奈只能曲线救国了。

改变启动广播的机制

首先注册开机广播

然后在开机广播中启动服务,这里我就不多写了

下面是服务中的的onCreate方法中的代码

public void onCreate() {        super.onCreate();        CallinFloatWindowBroadcast mBroadcastReceiver = CallinFloatWindowBroadcast.getInstance();        IntentFilter intentFilter = new IntentFilter();        intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);        registerReceiver(mBroadcastReceiver, intentFilter);    }

在Service中使用单例模式的广播,这样就保证了每次调用的receiver都是同一个对象

wm能成功移除了



1 0
原创粉丝点击