What happen when my Activity is destroyed when I'm using IntentService with ResultReceiver

≯℡__Kan透↙ 提交于 2019-12-04 03:02:32

Use a BroadcastReceiver on your Activity and register/unregister it in onResume() and onPause() respectively. You can use an IntentFilter to listen for an Intent from your IntentService.

In your IntentService, create an Action value for the IntentFilter and send a broadcast with that Action when you want to update:

public static final String ACTION = "com.example.yourapp.action.ACTION_TAG";

private void handleResult() {
    if (BuildConfig.DEBUG) {
        Log.v(TAG, "handleResult");
    }

    // Broadcast result
    Intent intent = new Intent(ACTION);
    intent.putExtra("your_extra", someValue);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

In your Activity:

private BroadcastReceiver mYourReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (BuildConfig.DEBUG) {
                Log.v(TAG, "onReceive");
            }



            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                // Update with content from bundle
            }
        }
    };

     @Override
     public void onResume() {
         super.onResume();

         if (BuildConfig.DEBUG) {
             Log.v(TAG, "onResume");
         }

         // Register broadcast receiver
         LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mYourReceiver, new IntentFilter(YourIntentService.ACTION));
    }

    @Override
    public void onPause() {
         super.onPause();
         if (BuildConfig.DEBUG) {
             Log.v(TAG, "onPause");
         }

         // Unregister broadcast receiver
         LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mYourReceiver);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!