send intent from service to activity

前端 未结 1 1815
轻奢々
轻奢々 2020-11-30 03:37

I\'m trying to return the result from an IntentSerivce to the mainactivity using an intent, but I can\'t get it to work. The IntentService

相关标签:
1条回答
  • 2020-11-30 03:50

    For this, you can use a BroadcastReceiver in your Activity.

    Here is a great example I use to communicate continuously between Service <> Activity using BroadcastReceivers.

    Here is another great example of communication between Service <> Activity. It uses Messenger and IncomingHandler.

    BroadcastReceiver

    I will make a quick example for your case.

    This is your BroadcastReceiver for your Activity. It is going to receive your String:

    //Your activity will respond to this action String
    public static final String RECEIVE_JSON = "com.your.package.RECEIVE_JSON";
    
    private BroadcastReceiver bReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(RECEIVE_JSON)) {
                String serviceJsonString = intent.getStringExtra("json");
                //Do something with the string
            }
        }
    };
    LocalBroadcastManager bManager;
    

    In your onCreate() of the activity

    bManager = LocalBroadcastManager.getInstance(this);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(RECEIVE_JSON);
    bManager.registerReceiver(bReceiver, intentFilter);
    

    In your onDestroy() of the activity, make sure you unregister the broadcastReceiver.

    bManager.unregisterReceiver(bReceiver);
    

    And finally, in your Service onStart(), do this:

    System.out.println("intent Received");
    String jsonString = rottenTomatoesSearch(intent.getStringExtra("query"));
    Intent RTReturn = new Intent(YourActivity.RECEIVE_JSON);
    RTReturn.putExtra("json", jsonString);
    LocalBroadcastManager.getInstance(this).sendBroadcast(RTReturn);
    

    and your Activity will receive the intent with that json in it as an extra

    0 讨论(0)
提交回复
热议问题