Where should I unregister in my own view?

My view has a registerReceiver with ACTION_TIME_TICK action, but I don't know where I should register.

If I do not, I will have a leak.

Here is the code:

 public class TimeIndicator extends ViewSwitcher { private void build(final Context context) { this.addView(View.inflate(context, R.layout.time_indicator, null)); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_TIME_TICK); context.registerReceiver(this.receiver, filter); } public final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("onReceive", intent.getAction()); } }; } 

Where should I unregister in my own view?

0
source share
2 answers
 @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); //add your code. getContext().unregisterReceiver(mReceiver); }; 
+3
source

This is not good behavior, your view has no context (it does not have a clear life cycle and it does not have life-cycle callback methods -onPause, onCreate .... -)

So what you need to do is reinstall this receiver in the first parent context object to which your view belongs. if it is a fragment of activity.

Then you can register the receiver using: onCreate() parent. and delete it when you no longer want to receive updates, or in onStop()

0
source

All Articles