如何访问一个 activity 以外的资源?

我有下面的代码:

Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
imageView.setImageBitmap(bMap);

但是获得以下的错误:

The method getResources() is undefined for the type ImageDownloader

如何访问资源呢?

在你的 ImageDownloader 类中创建一个新的 Constructor

public ImageDownloader(Activity mActivity){

// create a class level activity object in your ImageDownloader class.
   activity = mActivity;
}

现在需要改变下载代码:

Bitmap bMap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.icon);
imageView.setImageBitmap(bMap);

你需要把 Context 对象传递到 ImageDownloader类或者方法中,然后你可以在 Context对象中调用getResources()。让 Activity 和 Service 都继承 context。