Android BroadcastReceiver on startup - keep running when Activity is in Background

后端 未结 5 659
眼角桃花
眼角桃花 2020-11-22 05:34

I\'m monitoring incoming SMSs.

My app is working perfectly with a BroadcastReceiver. However it is working from an Activity and would like to keep the <

5条回答
  •  庸人自扰
    2020-11-22 05:58

    Service or Boot Completed is not mandatory

    In fact, you don't need to implement a Service or register to android.intent.action.BOOT_COMPLETED

    Some examples shows how to register/unregister a BroadcastReceiver when activity is created and destroyed. However, this is useful for intents that you expect only when app is opened (for internal communication between Service/Activity for example).

    However, in case of a SMS, you want to listen to the intent all the time (and not only when you app is opened).

    There's another way

    You can create a class which extends BroadcastReceiver and register to desired intents via AndroidManifest.xml. This way, the BroadcastReceiver will be indepedent from your Activity (and will not depend from Activity's Life Cycle)

    This way, your BroadcastReceiver will be notified automatically by Android as soon as an SMS arrive even if your app is closed.

    AndroidManifest.xml

    
    
        ...
        
        
    
        
            ....
            
                
                    
                
            
        
    
    

    MyCustomBroadcastReceiver.java

    public class MyCustomBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent != null) {
                String action = intent.getAction();
                if(action != null) {
                    if(action.equals("android.provider.Telephony.SMS_RECEIVED")) {
                        // DO YOUR STUFF
                    } else if (action.equals("ANOTHER ACTION")) {
                        // DO ANOTHER STUFF
                    }
                }
            }
        }
    }
    

    Notes

    You can add others intent-filters to AndroidManifest and handle all of them in same BroadcastReceiver.

    Start a Service only if you will perform a long task. You just need to display a notification or update some database, just use the code above.

提交回复
热议问题