简体   繁体   中英

Intent : Direct binding Activity to BroadcastReceiver without service?

First of all I wanted to give codes here but the codes are way to long, it can be found here

http://www.c-sharpcorner.com/article/creating-and-scheduling-alarms-in-android/

The codes in the article doesn't create service.

As per my understanding, BroadcastReceiver is used to serve an activity based on its corresponding Service ( via an intent ).

Normally we would declare such :

Intent serviceIntent = new Intent(MainActivity.this, CustomeService.class);
   startService(serviceIntent);
   registerReceiver(mReceiver, mIntentFilter);

where mReceiver will be something like :

private BroadcastReceiver mReceiver = new BroadcastReceiver() {

      @Override
      public void onReceive(Context context, Intent intent) {

       }
}

But there's something confusing me in AlarmManager class in the example that I shared by the link :

intent = new Intent(this, MyBroadcastReceiver.class);  
            pendingIntent = PendingIntent.getBroadcast(  
                    this.getApplicationContext(), 280192, intent, PendingIntent.FLAG_CANCEL_CURRENT);  
            alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);  
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + (i * 1000), 10000  
                    , pendingIntent);  

The line that is confusing me is this :

intent = new Intent(this, MyBroadcastReceiver.class);

the type of this MyBroadcastReceiver.class is BroadcastReceiver itself, and not Service.

So where's the Service that this MyBroadcastReceiver.class received broadcast from then?

Does BroadcastReceiver somehow create its own service?

the type of this MyBroadcastReceiver.class is BroadcastReceiver itself, and not Service

Correct. It is being used with PendingIntent. getBroadcast() , not getService()`.

So where's the Service that this MyBroadcastReceiver.class received broadcast from then?

Few broadcasts are sent by some Service , though that is certainly possible. In this case, the broadcast is being sent from a system process, as part of sending the PendingIntent , when the alarm time comes around.

Does BroadcastReceiver somehow create its own service?

I am not sure what you mean by "create" here. A BroadcastReceiver may delegate its work to a Service . That is a common pattern with AlarmManager : have the alarms trigger a WakefulBroadcastReceiver , which in turn delegates work to an IntentService . In that case, the reason for the indirection stems from the way that AlarmManager works with WakeLocks .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM