As a rule, the registration of the receiver (BroadcastReceiver) is carried out at the time of the creation of the Activity, the registration is canceled when the Activity is deleted. I want to attach this process to a button press, that is: Press the button - the service and receiver start. When the service sends a message, the receiver is disabled. The problem is that each button press registers a new receiver, if the βoldβ is not yet disconnected. To eliminate double (triple, etc.) registration of the receiver, I introduced an additional variable lReceiverOn, the contents of which I check before registration.
public void clickLayout(View view) { startService(new Intent(this, MyServiceFlash.class).putExtra("Mode", 3)); //ΠΠ°ΠΏΡΡΠΊ ΡΠ΅ΡΠ²ΠΈΡΠ°, ΠΎΡΠΊΡΠ΄Π° ΠΆΠ΄Π΅ΠΌ ΡΠΎΠΎΠ±ΡΠ΅Π½ΠΈΠΉ if (! lReceiverOn) { LocalBroadcastManager.getInstance(this).registerReceiver( mReceiver, new IntentFilter("SrvIntent")); // ΡΠ΅Π³ΠΈΡΡΡΠΈΡΡΠ΅ΠΌ ΠΏΡΠΈΠ΅ΠΌΠ½ΠΈΠΊ ΡΠΎΠΎΠ±ΡΠ΅Π½ΠΈΠΉ ΠΈΠ· ΡΠ΅ΡΠ²ΠΈΡΠ° lReceiverOn = true; // ΠΏΠ΅ΡΠ΅ΠΌΠ΅Π½Π½Π°Ρ ΠΊΠΎΠ½ΡΡΠΎΠ»Ρ Π·Π°ΠΏΡΡΠΊΠ° ΠΏΡΠΈΠ΅ΠΌΠ½ΠΈΠΊΠ° } ... private BroadcastReceiver mReceiver = new BroadcastReceiver() { // ΠΏΡΠΈΠ΅ΠΌΠ½ΠΈΠΊ ΡΠΎΠΎΠ±ΡΠ΅Π½ΠΈΠΉ ΠΈΠ· ΡΠ΅ΡΠ²ΠΈΡΠ° @Override public void onReceive(Context context, Intent intent) { ... LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mReceiver); // ΠΎΡΠΌΠ΅Π½Π° ΡΠ΅Π³ΠΈΡΡΡΠ°ΡΠΈΠΈ lReceiverOn=false; } }; Question: Is it possible to do without this variable, to determine that the receiver is running? Naively tried (mReceiver! = Null), does not work. Could not find other methods.
onCreate()and register when pressed - Barmaley