2017-01-20 60 views
2

我正在構建一個壁紙應用程序。 我有一個設置壁紙的按鈕。 我想要做的是檢查壁紙是否下載,如果是設置壁紙 - 如果沒有,下載並設置壁紙。在WallpaperManager的廣播接收器上額外的意圖

我檢查是否存在帶有ID的文件(例如26748.jpg),如果是,我成功設置壁紙,如果它不存在,我下載它 - 但我無法設置它。

我有一個BroadcastReceiver設置:

<receiver android:name=".SinglePhotoActivity$CheckDownloadComplete"> 
     <intent-filter> 
      <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/> 
     </intent-filter> 
    </receiver> 

它顯示一個簡單的保存消息:

public static class CheckDownloadComplete extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Toast.makeText(context, "Saved!", Toast.LENGTH_SHORT).show(); 
    } 

} 

的問題是,我有兩種類型設置壁紙:一,如果壁紙已經下載了,如果沒有,壁紙也會下載。我做了一點研究,發現這種類型的廣播接收機不能真正包含任何附加的意圖。我唯一能做的就是在我的DownloadManager的請求中設置一個描述,然後檢查onReceive中的描述。

所以,如果圖像已經下載,我想顯示一個簡單的吐司。如果沒有,然後下載它,然後在OnReceive下載完成後運行我的設置壁紙的代碼。

還有沒有更好的做法呢?

+1

你從哪裏讀到你不能在這個廣播中有一個額外的啓示者? –

回答

0

檢查壁紙是否已經下載。

創建一個至少包含兩列的數據庫表。

1.Downloaded wallpaper url 2.Downloaded image local path(from where you will set it to wallpaper)

每次嘗試下載壁紙時,首先請從數據庫表中檢查中是否已存在url。對於這個我使用的是sugarorm,你可以使用任何數據庫。你可以在sugarorm這樣做。

DownloadedWallpapers mDownloadedWallpaper = null; 

    try { 
     mDownloadedWallpaper = DownloadedWallpapers.find(DownloadedWallpapers.class, "url=?", imageUrl).get(0); 
    } catch (Exception ex) {} 

    if (mDownloadedWallpaper == null) 
     // run your downloading code here and on download set wallpaper 
    else 
     // run set wallpaper code here 

在其他數據庫中,過程是相同的。只需檢查網址是否存在於數據庫中。

下載後發送包含本地文件路徑的廣播。

Intent mIntent = new Intent(context,WallpaperReceiver.class); 
mIntent.putExtra("local_path", downloadedFilePath); 
sendBroadcast(mIntent); 

在廣播接收機運行牆紙設置代碼。

對我來說,這是一個乾淨,工作和簡單的解決方案。歡呼聲:)