我目前正在尝试使用 Retrofit 构建 Muzei 扩展,就像 Roman 在他的示例中使用的示例一样。
我无法真正理解改造,但这就是我所拥有的
ArtSource.java
public class ArtSource extends RemoteMuzeiArtSource {
private static final String TAG = "The Muzei Collection";
private static final String SOURCE_NAME = "The Muzei Collection";
private static final int ROTATE_TIME_MILLIS = 3 * 60 * 60 * 1000; // rotate every 3 hours
public ArtSource() {
super(SOURCE_NAME);
}
@Override
public void onCreate() {
super.onCreate();
setUserCommands(BUILTIN_COMMAND_ID_NEXT_ARTWORK);
}
@Override
protected void onTryUpdate(int reason) throws RetryException {
String currentToken = (getCurrentArtwork() != null) ? getCurrentArtwork().getToken() : null;
RestAdapter restAdapter = new RestAdapter.Builder()
.setServer("http://elliothesp.co.uk")
.build();
ArtService service = restAdapter.create(ArtService.class);
PhotosResponse response = service.getPopularPhotos();
if (response == null || response.photos == null) {
throw new RetryException();
}
if (response.photos.size() == 0) {
Log.w(TAG, "No photos returned from API.");
scheduleUpdate(System.currentTimeMillis() + ROTATE_TIME_MILLIS);
return;
}
Random random = new Random();
Photo photo;
String token;
while (true) {
photo = response.photos.get(random.nextInt(response.photos.size()));
token = Integer.toString(photo.id);
if (response.photos.size() <= 1 || !TextUtils.equals(token, currentToken)) {
break;
}
}
publishArtwork(new Artwork.Builder()
.title(photo.title)
.byline(photo.user)
.imageUri(Uri.parse(photo.url))
.token(token)
.viewIntent(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.com")))
.build());
scheduleUpdate(System.currentTimeMillis() + ROTATE_TIME_MILLIS);
}
}
ArtService.java
interface ArtService {
@GET("/muzei.php")
PhotosResponse getPopularPhotos();
static class PhotosResponse {
List<Photo> photos;
}
static class Photo {
int id;
String user;
String title;
String url;
}
}
基本上,我试图从http://elliothesp.co.uk/muzei.php获取 JSON并将每个项目传递给 publishArtwork。它运行异常,因为它无法从 JSON 提要中找到任何照片,我不知道如何让它工作