How to have Android Service communicate with Activity

前端 未结 13 2109
说谎
说谎 2020-11-22 02:54

I\'m writing my first Android application and trying to get my head around communication between services and activities. I have a Service that will run in the background an

13条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 03:34

    The asker has probably long since moved past this, but in case someone else searches for this...

    There's another way to handle this, which I think might be the simplest.

    Add a BroadcastReceiver to your activity. Register it to receive some custom intent in onResume and unregister it in onPause. Then send out that intent from your service when you want to send out your status updates or what have you.

    Make sure you wouldn't be unhappy if some other app listened for your Intent (could anyone do anything malicious?), but beyond that, you should be alright.

    Code sample was requested:

    In my service, I have this:

    // Do stuff that alters the content of my local SQLite Database
    sendBroadcast(new Intent(RefreshTask.REFRESH_DATA_INTENT));
    

    (RefreshTask.REFRESH_DATA_INTENT is just a constant string.)

    In my listening activity, I define my BroadcastReceiver:

    private class DataUpdateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(RefreshTask.REFRESH_DATA_INTENT)) {
              // Do stuff - maybe update my view based on the changed DB contents
            }
        }
    }
    

    I declare my receiver at the top of the class:

    private DataUpdateReceiver dataUpdateReceiver;
    

    I override onResume to add this:

    if (dataUpdateReceiver == null) dataUpdateReceiver = new DataUpdateReceiver();
    IntentFilter intentFilter = new IntentFilter(RefreshTask.REFRESH_DATA_INTENT);
    registerReceiver(dataUpdateReceiver, intentFilter);
    

    And I override onPause to add:

    if (dataUpdateReceiver != null) unregisterReceiver(dataUpdateReceiver);
    

    Now my activity is listening for my service to say "Hey, go update yourself." I could pass data in the Intent instead of updating database tables and then going back to find the changes within my activity, but since I want the changes to persist anyway, it makes sense to pass the data via DB.

提交回复
热议问题