Android: How to getExtras from service that send an intent via broadcast programmtically WITHOUT BROADCASTRECEIVER? -


I would like to know how to pass data between service and an activity without broadcast.

This is what I can not do:

  1. I have a service which periodically sends an intent through broadcast.
  2. I want to get an addition of this intention from an activity when I want, without any broadcast receiver.

    I tried to use this code:

      \\ service string BROADCAST_ACTION = "ACTION"; Send Intent SendToUI = New Intent (BROADCAST_ACTION); SendToUI.putExtra ("key", "value"); SendBroadcast (sendToUI); \ Activity IntentFilter IF = New Intent Filter (MyService.BROADCAST_ACTION); Intent intention = c. Registrar receiver (tap, if); Bundle Extras = Intent. Getextros (); If (extra! = Null) {string string = intent.Tastring extra ("key"); }   

    but I get nullpointerexception because intent is always null (I get the nullpointerexception ) not in bundle extras but purpose of intent LINE).

    To do this, hang the broadcast you "from time to time" "So that activity can get it when he wants it.

    In your service, you will get this broadcast "sticky", like this:

      // service string BROADCAST_ACTION = "action"; Send Intent SendToUI = New Intent (BROADCAST_ACTION); SendToUI.putExtra ("key", "value"); SendStickyBroadcast (sendToUI);   

    You must have BROADCAST_STICKY permission to use this API. If you do not catch that permission, then security exceptions will be thrown.

    Edit: Add code to read activity:

      // Activity IntentFilter IF = new intent filter (MyService.BROADCAST_ACTION); Intent intention = c. Registrar receiver (tap, if); If (intent! = Null & intent.hasExtra ("key")) {string string = intent.getStringExtra ("key"); // now do something with it ...}   

    Also, I was suggesting that you are using "MyService.BROADCAST_ACTION" to include your fully qualified package name Change the string. The reason for this is that if you just use "action", then there may be other applications that are also sending around the sticky broadcast with that action and the purpose for which you intend to (I.e.: sent by your service). Use something like this (in your service category):

      string BROADCAST_ACTION = "com.mycompany.myapplication.ACTION";    

Comments