Here are the examples of the java api class com.google.android.apps.muzei.api.Artwork taken from open source projects.
1. NewWallpaperNotificationReceiver#markNotificationRead()
Project: muzei
File: NewWallpaperNotificationReceiver.java
File: NewWallpaperNotificationReceiver.java
public static void markNotificationRead(Context context) { SourceManager sm = SourceManager.getInstance(context); Artwork currentArtwork = sm.getCurrentArtwork(); if (currentArtwork == null || currentArtwork.getImageUri() == null) { return; } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putString(PREF_LAST_SEEN_NOTIFICATION_IMAGE_URI, currentArtwork.getImageUri().toString()).apply(); NotificationManagerCompat nm = NotificationManagerCompat.from(context); nm.cancel(NOTIFICATION_ID); }
2. FeaturedArtSource#onTryUpdate()
Project: muzei
File: FeaturedArtSource.java
File: FeaturedArtSource.java
@Override protected void onTryUpdate(int reason) throws RetryException { Artwork currentArtwork = getCurrentArtwork(); Artwork artwork; JSONObject jsonObject; try { jsonObject = IOUtil.fetchJsonObject(QUERY_URL); artwork = Artwork.fromJson(jsonObject); } catch (JSONExceptionIOException | e) { LOGE(TAG, "Error reading JSON", e); throw new RetryException(e); } if (artwork != null && currentArtwork != null && artwork.getImageUri() != null && artwork.getImageUri().equals(currentArtwork.getImageUri())) { LOGD(TAG, "Skipping update of same artwork."); } else { LOGD(TAG, "Publishing artwork update: " + artwork); if (artwork != null && jsonObject != null) { artwork.setMetaFont(Artwork.FONT_TYPE_ELEGANT); publishArtwork(artwork); } } Date nextTime = null; String nextTimeStr = jsonObject.optString("nextTime"); if (!TextUtils.isEmpty(nextTimeStr)) { int len = nextTimeStr.length(); if (len > 4 && nextTimeStr.charAt(len - 3) == ':') { nextTimeStr = nextTimeStr.substring(0, len - 3) + nextTimeStr.substring(len - 2); } try { nextTime = sDateFormatTZ.parse(nextTimeStr); } catch (ParseException e) { try { sDateFormatLocal.setTimeZone(TimeZone.getDefault()); nextTime = sDateFormatLocal.parse(nextTimeStr); } catch (ParseException e2) { LOGE(TAG, "Can't schedule update; " + "invalid date format '" + nextTimeStr + "'", e2); } } } boolean scheduleFallback = true; if (nextTime != null) { // jitter by up to N milliseconds scheduleUpdate(nextTime.getTime() + sRandom.nextInt(MAX_JITTER_MILLIS)); scheduleFallback = false; } if (scheduleFallback) { // No next time, default to checking in 12 hours scheduleUpdate(System.currentTimeMillis() + 12 * 60 * 60 * 1000); } }
3. GaufrerWallpaperSource#onTryUpdate()
Project: polar-dashboard
File: GaufrerWallpaperSource.java
File: GaufrerWallpaperSource.java
@Override protected void onTryUpdate(int reason) throws RetryException { WallpaperUtils.WallpapersHolder wallpapers; try { wallpapers = WallpaperUtils.getAll(this, !WallpaperUtils.didExpire(this)); } catch (Exception e) { Log.d(GaufrerWallpaperSource.class.getSimpleName(), String.format("Failed to retrieve wallpapers for Muzei... %s", e.getMessage())); throw new RetryException(); } if (wallpapers == null || wallpapers.length() == 0) { Log.d(GaufrerWallpaperSource.class.getSimpleName(), "No wallpapers were found for Muzei."); throw new RetryException(); } int currentActive = getActiveIndex() + 1; if (currentActive > wallpapers.length() - 1) currentActive = 0; setActiveIndex(currentActive); WallpaperUtils.Wallpaper currentWallpaper = wallpapers.get(currentActive); Log.d(GaufrerWallpaperSource.class.getSimpleName(), String.format("Publishing artwork to Muzei: %s", currentWallpaper.url)); final Artwork currentArt = new Artwork.Builder().imageUri(Uri.parse(currentWallpaper.url)).title(currentWallpaper.name).byline(currentWallpaper.author).viewIntent(new Intent(getApplicationContext(), MainActivity.class).setAction(Intent.ACTION_SET_WALLPAPER).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)).token(String.format("%s:%s", currentWallpaper.name, currentWallpaper.author)).build(); publishArtwork(currentArt); scheduleUpdate(System.currentTimeMillis() + ROTATE_TIME_MILLIS); }
4. ArtworkCacheIntentService#processDataItem()
Project: muzei
File: ArtworkCacheIntentService.java
File: ArtworkCacheIntentService.java
private boolean processDataItem(GoogleApiClient googleApiClient, DataItem dataItem) { if (!dataItem.getUri().getPath().equals("/artwork")) { Log.w(TAG, "Ignoring data item " + dataItem.getUri().getPath()); return false; } DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItem); DataMap artworkDataMap = dataMapItem.getDataMap().getDataMap("artwork"); if (artworkDataMap == null) { Log.w(TAG, "No artwork in datamap."); return false; } final Artwork artwork = Artwork.fromBundle(artworkDataMap.toBundle()); final Asset asset = dataMapItem.getDataMap().getAsset("image"); if (asset == null) { Log.w(TAG, "No image asset in datamap."); return false; } // Convert asset into a file descriptor and block until it's ready final DataApi.GetFdForAssetResult getFdForAssetResult = Wearable.DataApi.getFdForAsset(googleApiClient, asset).await(); InputStream assetInputStream = getFdForAssetResult.getInputStream(); if (assetInputStream == null) { Log.w(TAG, "Empty asset input stream (probably an unknown asset)."); return false; } Bitmap image = BitmapFactory.decodeStream(assetInputStream); if (image == null) { Log.w(TAG, "Couldn't decode a bitmap from the stream."); return false; } File localCache = new File(getCacheDir(), "cache.png"); FileOutputStream out = null; try { out = new FileOutputStream(localCache); image.compress(Bitmap.CompressFormat.PNG, 100, out); } catch (IOException e) { Log.e(TAG, "Error writing local cache", e); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { Log.e(TAG, "Error closing local cache file", e); } } enableComponents(FullScreenActivity.class); if (MuzeiProvider.saveCurrentArtworkLocation(this, localCache)) { getContentResolver().insert(MuzeiContract.Artwork.CONTENT_URI, artwork.toContentValues()); } return true; }
5. RealRenderController#openDownloadedCurrentArtwork()
Project: muzei
File: RealRenderController.java
File: RealRenderController.java
@Override protected BitmapRegionLoader openDownloadedCurrentArtwork(boolean forceReload) { SourceManager sm = SourceManager.getInstance(mContext); Artwork currentArtwork = sm.getCurrentArtwork(); if (currentArtwork == null) { return null; } ArtworkCache artworkCache = ArtworkCache.getInstance(mContext); File file = artworkCache.getArtworkCacheFile(sm.getSelectedSource(), currentArtwork); if (file == null) { return null; } if (!file.exists() || file.length() == 0) { mContext.startService(TaskQueueService.getDownloadCurrentArtworkIntent(mContext)); return null; } if (mLastLoadedPath != null && mLastLoadedPath.equals(file.getAbsolutePath()) && !forceReload) { return null; } // Check if there's rotation int rotation = 0; try { ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath()); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch(orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotation = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotation = 270; break; } LOGD(TAG, "Loading artwork with rotation: " + rotation); } catch (IOException e) { LOGW(TAG, "Couldn't open EXIF interface on file: " + file.getAbsolutePath(), e); } // Load the stream try { BitmapRegionLoader loader = BitmapRegionLoader.newInstance(new FileInputStream(file), rotation); if (MuzeiProvider.saveCurrentArtworkLocation(mContext, file)) { mContext.getContentResolver().insert(MuzeiContract.Artwork.CONTENT_URI, currentArtwork.toContentValues()); } NewWallpaperNotificationReceiver.maybeShowNewArtworkNotification(mContext, currentArtwork, loader); WearableController.updateArtwork(mContext, currentArtwork, loader); mLastLoadedPath = file.getAbsolutePath(); return loader; } catch (IOException e) { LOGE(TAG, "Error loading image: " + file.getAbsolutePath() + " from " + currentArtwork.getImageUri(), e); return null; } }
6. GalleryArtSource#publishNextArtwork()
Project: muzei
File: GalleryArtSource.java
File: GalleryArtSource.java
private void publishNextArtwork(Uri forceUri) { // schedule next scheduleNext(); List<Uri> chosenUris = mStore.getChosenUris(); int numChosenUris = (chosenUris != null) ? chosenUris.size() : 0; Artwork currentArtwork = getCurrentArtwork(); String lastToken = (currentArtwork != null) ? currentArtwork.getToken() : null; boolean useStoredFile = true; Uri imageUri; Random random = new Random(); if (forceUri != null) { imageUri = forceUri; } else if (numChosenUris > 0) { while (true) { imageUri = chosenUris.get(random.nextInt(chosenUris.size())); if (numChosenUris <= 1 || !imageUri.toString().equals(lastToken)) { break; } } } else { useStoredFile = false; if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { LOGW(TAG, "Missing read external storage permission."); return; } Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ImagesQuery.PROJECTION, MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " NOT LIKE '%Screenshots%'", null, null); if (cursor == null) { LOGW(TAG, "Empty cursor."); return; } int count = cursor.getCount(); if (count == 0) { LOGE(TAG, "No photos in the gallery."); return; } while (true) { cursor.moveToPosition(random.nextInt(count)); imageUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cursor.getLong(ImagesQuery._ID)); if (!imageUri.toString().equals(lastToken)) { break; } } cursor.close(); } String token = imageUri.toString(); // Retrieve metadata for item GalleryStore.Metadata metadata = getOrCreateMetadata(imageUri); // Publish the actual artwork String title; if (metadata.datetime > 0) { title = DateUtils.formatDateTime(this, metadata.datetime, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY); } else { title = getString(R.string.gallery_source_from_gallery); } String byline; if (!TextUtils.isEmpty(metadata.location)) { byline = metadata.location; } else { byline = getString(R.string.gallery_source_touch_to_view); } Uri finalImageUri = imageUri; if (useStoredFile) { // Previously stored in handleAddChosenUris finalImageUri = Uri.fromFile(getStoredFileForUri(this, imageUri)); } publishArtwork(new Artwork.Builder().imageUri(finalImageUri).title(title).byline(byline).token(token).viewIntent(new Intent(Intent.ACTION_VIEW).setDataAndType(finalImageUri, "image/jpeg")).build()); }
7. FeaturedArtSource#onSubscriberAdded()
Project: muzei
File: FeaturedArtSource.java
File: FeaturedArtSource.java
@Override protected void onSubscriberAdded(ComponentName subscriber) { super.onSubscriberAdded(subscriber); Artwork currentArtwork = getCurrentArtwork(); if (currentArtwork != null && !"initial".equals(currentArtwork.getToken())) { // TODO: is this really necessary? // When a subscriber is added, manually try a fetch, unless this is the // first update onUpdate(UPDATE_REASON_OTHER); } }
8. ArtworkCache#maybeDownloadCurrentArtworkSync()
Project: muzei
File: ArtworkCache.java
File: ArtworkCache.java
public synchronized void maybeDownloadCurrentArtworkSync() { SourceManager sm = SourceManager.getInstance(mApplicationContext); ComponentName selectedSource = sm.getSelectedSource(); Artwork currentArtwork = sm.getCurrentArtwork(); if (currentArtwork == null) { return; } File destFile = getArtworkCacheFile(selectedSource, currentArtwork); if (destFile == null) { return; } if (destFile.exists() && destFile.length() > 0) { EventBus.getDefault().postSticky(new ArtworkLoadingStateChangedEvent(false, false)); EventBus.getDefault().post(new CurrentArtworkDownloadedEvent()); return; } // ensure cache root for this source exists destFile.getParentFile().mkdirs(); EventBus.getDefault().postSticky(new ArtworkLoadingStateChangedEvent(true, false)); InputStream in; try { in = IOUtil.openUri(mApplicationContext, currentArtwork.getImageUri(), "image/"); } catch (IOUtil.OpenUriException e) { LOGE(TAG, "Error downloading current artwork. URI: " + currentArtwork.getImageUri(), e); if (e.isRetryable()) { scheduleRetryArtworkDownload(); } EventBus.getDefault().postSticky(new ArtworkLoadingStateChangedEvent(false, true)); return; } cancelArtworkDownloadRetries(); // Input stream successfully opened. Save to cache file try { File tempFile = new File(mArtCacheRoot, "temp.download"); IOUtil.readFullyWriteToFile(in, tempFile); destFile.delete(); if (!tempFile.renameTo(destFile)) { throw new IOException("Couldn't move temp artwork file to final cache location."); } // Attempt to parse the newly downloaded file as an image, ensuring it is in a valid format BitmapRegionLoader.newInstance(new FileInputStream(destFile)); } catch (IOException e) { LOGE(TAG, "Error caching and loading the current artwork. URI: " + currentArtwork.getImageUri(), e); destFile.delete(); EventBus.getDefault().postSticky(new ArtworkLoadingStateChangedEvent(false, true)); scheduleRetryArtworkDownload(); return; } cleanupCache(selectedSource); EventBus.getDefault().postSticky(new ArtworkLoadingStateChangedEvent(false, false)); EventBus.getDefault().post(new CurrentArtworkDownloadedEvent()); }
9. ArtworkUpdateService#onHandleIntent()
Project: muzei
File: ArtworkUpdateService.java
File: ArtworkUpdateService.java
@Override protected void onHandleIntent(final Intent intent) { ComponentName widget = new ComponentName(this, MuzeiAppWidgetProvider.class); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(widget); if (appWidgetIds.length == 0) { // No app widgets, nothing to do Log.w(TAG, "No AppWidgets found"); return; } Artwork currentArtwork = MuzeiContract.Artwork.getCurrentArtwork(this); if (currentArtwork == null) { Log.w(TAG, "No current artwork found"); return; } String contentDescription = !TextUtils.isEmpty(currentArtwork.getTitle()) ? currentArtwork.getTitle() : currentArtwork.getByline(); Bitmap image; try { image = MuzeiContract.Artwork.getCurrentArtworkBitmap(this); // getCurrentArtworkBitmap is a naive method so we manually reduce the size based on the screen size // Consider using BitmapFactory.decodeStream(contentResolver.openInputStream(CONTENT_URI), options) // where options subsamples the image to the appropriate size if you don't need to full size image image = scaleBitmap(image); } catch (FileNotFoundException e) { Log.w(ArtworkUpdateService.class.getSimpleName(), "Could not find current artwork image", e); return; } if (image == null) { Log.w(TAG, "No current artwork bitmap found"); return; } // Update the widget(s) with the new artwork information PackageManager packageManager = getPackageManager(); Intent launchIntent = packageManager.getLaunchIntentForPackage("net.nurik.roman.muzei"); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT); for (int widgetId : appWidgetIds) { RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget); remoteViews.setContentDescription(R.id.background, contentDescription); remoteViews.setImageViewBitmap(R.id.background, image); remoteViews.setOnClickPendingIntent(R.id.background, pendingIntent); appWidgetManager.updateAppWidget(widgetId, remoteViews); } }
10. MuzeiArtworkImageLoader#hasMuzeiArtwork()
Project: FORMWatchFace
File: MuzeiArtworkImageLoader.java
File: MuzeiArtworkImageLoader.java
public static boolean hasMuzeiArtwork(Context context) { Artwork currentArtwork = MuzeiContract.Artwork.getCurrentArtwork(context); return currentArtwork != null; }