android – IntentService响应死ResultReceiver

前端之家收集整理的这篇文章主要介绍了android – IntentService响应死ResultReceiver前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
活动实例化ResultReceiver并覆盖onReceiveResult.然后,活动将Intent发送到IntentService,并将ResultReceiver包含为额外的.一旦IntentService完成处理,它就会将消息发送回ResultReceiver并在onReceiveResult中处理它.

问题是如果用户导航离开Activity,结果仍然会发送回ResultReceiver,从而导致所有类型的问题.有没有办法阻止这种行为?我已经尝试在活动的onDestroy()中停止IntentService,但结果仍然被发回.

这是一个活动示例

public class Foo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent i = new Intent(this,SampleIntentService.class);
        i.putExtra("receiver",mReceiver);
        startService(i);
    }

    @Override
    public void onDestroy() {
        stopService(new Intent(this,SampleIntentService.class));
        mReceiver = null;
        super.onDestroy();
    }

    ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
        @Override
        protected void onReceiveResult(int resultCode,Bundle resultData) {
            // Handle response from IntentService here
        }
    };
}

这是一个示例IntentService

public class SampleIntentService extends IntentService {
    public SampleIntentService() {
        super(SampleIntentService.class.getName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {
    ResultReceiver rec = intent.getParcelableExtra("receiver");
        if (rec != null) {
            rec.send(200,null);
        }
    }
}

解决方法

我通过创建自定义ResultReceiver解决了这个问题,如下所示.
public class SampleResultReceiver extends ResultReceiver {
    private Receiver mReceiver;

    public SampleResultReceiver(Handler handler) {
        super(handler);
    }

    public void setReceiver(Receiver receiver) {
        mReceiver = receiver;
    }

    public interface Receiver {
        void onReceiveResult(int resultCode,Bundle resultData);
    }

    @Override
    protected void onReceiveResult(int resultCode,Bundle resultData) {
        if (mReceiver != null) {
            mReceiver.onReceiveResult(resultCode,resultData);
        }
    }
}

然后在我的活动中,我执行以下操作:

public class Foo extends Activity implements Receiver {
    private SampleResultReceiver mReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mReceiver = new SampleResultReceiver(new Handler());
        mReceiver.setReceiver(this);

        Intent i = new Intent(this,mReceiver);
        startService(i);
    }

    @Override
    public void onDestroy() {
        if (mReceiver != null) {
            mReceiver.setReceiver(null);
        }
        super.onDestroy();
    }

    @Override
    protected void onReceiveResult(int resultCode,Bundle resultData) {
        // Handle response from IntentService here
    }
}

这将导致发送到您的自定义ResultReceiver的任何消息在活动被销毁后无处可能结束:)

原文链接:https://www.f2er.com/android/313036.html

猜你在找的Android相关文章