我可以"绑定"图像文件到ImageView?

时间:2017-05-11 21:33:13

标签: android imageview android-databinding

我有一个Android应用,其中包含每个用户都有头像的用户列表。头像图像文件存储为apps cache文件夹中的本地 .png 文件。有时,另一个服务更新具有更新当前的头像png文件(但没有正常的顺序),我想让我的头像ImageView更新与新的 .png 文件一样它们被保存到磁盘。

我已经尝试了对ImageView进行子类化并为其添加FileObserver属性,但是,这似乎并不是最有效的。

有没有人对如何生活"有任何建议?将 .png 绑定到ImageView,以便在磁盘上的映像文件发生更改时/它会更新?

我不确定是否应该查看 DataBinding ,因为这对我来说似乎有点过分了。

1 个答案:

答案 0 :(得分:0)

您可以在活动中注册BroadcastReceiver并从服务中接收通知

首先,您需要像这样创建BroadcastReceiver的实现:

public class YourBroadcastReceiver extends BroadcastReceiver {
    /**
     * Listener interface for received broadcast messages.
     */
    public interface YourBroadcastListener {
        void receivedBroadcast();
    }

    /**
     * The Intent action that this Receiver should filter for.
     */
    public static final String ACTION = "com.your.package.IMAGES_UPDATED";

    private final YourBroadcastListener mListener;

    public YourBroadcastReceiver(YourBroadcastListener listener) {
        mListener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (mListener != null)
            mListener.receivedBroadcast();
    }
}

接下来,您需要在活动中注册YourBroadcastReceiver

public class MainActivity extends Activity implements YourBroadcastListener {

    private YourBroadcastReceiver mReceiver;

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

        if(mReceiver == null){
            mReceiver = new YourBroadcastReceiver(this);
            registerReceiver(mReceiver, new IntentFilter(YourBroadcastReceiver.ACTION));
        }
    }


    @Override
    protected void onPause() {
        super.onPause();

        if(mReceiver != null){
            unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }

    @Override
    public void receivedBroadcast() {
        // Received a broadcast notification that the images has changed - reload it
    }
}

最后,您的服务需要向您的活动发送brodcast通知:

Intent i = new Intent("com.your.package.IMAGES_UPDATED");
sendBroadcast(i);

请注意:您的操作字符串必须是唯一的,以避免与其他应用程序发生冲突。