Search code examples
androidandroid-broadcast

BroadcastReceiver class that detects activity going onPause


I'm sorry I know when we mix BroadcastReceivers with activity life-cycle we cause the brain to have lots of errors and malfunction. I need help my brain stopped and my question is simple.

Is there a way to have BroadcastReceiver class that detect an activity going onPause() method ? if yes then how would that class be?


Solution

  • the only thing i can think of it on your activity send a costume broadcast intent that one of your receivers.

    e.g:

    action:

      public static final String CUSTOM_INTENT = "example.com.intent.action.ActivityGoingOnPause";
    

    activity onPause:

      protected void onPause() {
         Intent i = new Intent();
         i.setAction(CUSTOM_INTENT);
         context.sendBroadcast(i);
      }
    

    manifest:

        <receiver android:name=".YourReceiver" android:enabled="true">  
            <intent-filter>
                <action android:name="example.com.intent.action.ActivityGoingOnPause"></action>
            </intent-filter>
        </receiver>
    

    reciver:

     public class YourReceiver extends BroadcastReceiver {
         @Override
         public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(YourActivity.CUSTOM_INTENT)) {
              //do your thing
            }
         }
     }
    

    Hope this helps