Passing context to Handler

岁酱吖の 提交于 2019-12-04 09:52:28

What if you create a subclass which extends Handler? That way you could pass any parameters you want.

But just out of curiosity, why does the Blossom object require the context object? It's usually best to separate your logic from GUI dependencies.

Create a class that extends Handler, and store a weak reference to the context. This will help prevent some memory issues.

public class SomeHandler extends Handler {

    // A weak reference to the enclosing context
    private WeakReference<Context> mContext;

    public SomeHandler (Context context) {
        mContext = new WeakReference<Context>(context);
    }

    public void handleMessage(Message msg) {

        // Get an actual reference to the DownloadActivity
        // from the WeakReference.
        Context context=mContext.get();
        ...
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!