diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2013-04-21 17:01:26 +0400 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2013-04-21 17:01:26 +0400 |
| commit | 0b2345344bb16bdb70470b630008e194e3a0133c (patch) | |
| tree | e0a09ed38e37ef358d67a2c9b0ed81ceb5421d63 /src/org/fox/ttrss/util | |
| parent | b67e6ff9c54ef7f377ffc9b0b4f7702ff695188f (diff) | |
support actionbarsherlock
Diffstat (limited to 'src/org/fox/ttrss/util')
| -rw-r--r-- | src/org/fox/ttrss/util/AppRater.java | 208 | ||||
| -rw-r--r-- | src/org/fox/ttrss/util/DatabaseHelper.java | 172 | ||||
| -rw-r--r-- | src/org/fox/ttrss/util/HeadlinesRequest.java | 166 | ||||
| -rw-r--r-- | src/org/fox/ttrss/util/ImageCacheService.java | 422 | ||||
| -rw-r--r-- | src/org/fox/ttrss/util/PrefsBackupAgent.java | 38 |
5 files changed, 503 insertions, 503 deletions
diff --git a/src/org/fox/ttrss/util/AppRater.java b/src/org/fox/ttrss/util/AppRater.java index 08163710..21dccdff 100644 --- a/src/org/fox/ttrss/util/AppRater.java +++ b/src/org/fox/ttrss/util/AppRater.java @@ -1,105 +1,105 @@ -package org.fox.ttrss.util;
-
-// From http://androidsnippets.com/prompt-engaged-users-to-rate-your-app-in-the-android-market-appirater
-
-import android.app.Dialog;
-import android.content.ActivityNotFoundException;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.net.Uri;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.widget.Button;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-
-public class AppRater {
- private final static String APP_TITLE = "Tiny Tiny RSS";
- private final static String APP_PNAME = "org.fox.ttrss";
-
- private final static int DAYS_UNTIL_PROMPT = 3;
- private final static int LAUNCHES_UNTIL_PROMPT = 7;
-
- public static void appLaunched(Context mContext) {
- SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
-
- if (prefs.getBoolean("dontshowagain", false)) { return ; }
-
- SharedPreferences.Editor editor = prefs.edit();
-
- // Increment launch counter
- long launch_count = prefs.getLong("launch_count", 0) + 1;
- editor.putLong("launch_count", launch_count);
-
- // Get date of first launch
- Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
- if (date_firstLaunch == 0) {
- date_firstLaunch = System.currentTimeMillis();
- editor.putLong("date_firstlaunch", date_firstLaunch);
- }
-
- // Wait at least n days before opening
- if (launch_count >= LAUNCHES_UNTIL_PROMPT &&
- !prefs.getBoolean("dontshowagain", false) &&
- System.currentTimeMillis() >= date_firstLaunch + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
-
- showRateDialog(mContext, editor);
- }
-
- editor.commit();
- }
-
- public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
- final Dialog dialog = new Dialog(mContext);
- dialog.setTitle("Rate " + APP_TITLE);
-
- LinearLayout ll = new LinearLayout(mContext);
- ll.setOrientation(LinearLayout.VERTICAL);
-
- TextView tv = new TextView(mContext);
- tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
- tv.setWidth(240);
- tv.setPadding(4, 0, 4, 10);
- ll.addView(tv);
-
- Button b1 = new Button(mContext);
- b1.setText("Rate " + APP_TITLE);
- b1.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- try {
- mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
- } catch (ActivityNotFoundException e) {
- mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + APP_PNAME)));
- }
- dialog.dismiss();
- }
- });
- ll.addView(b1);
-
- Button b2 = new Button(mContext);
- b2.setText("Remind me later");
- b2.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- dialog.dismiss();
- }
- });
- ll.addView(b2);
-
- Button b3 = new Button(mContext);
- b3.setText("No, thanks");
- b3.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- if (editor != null) {
- editor.putBoolean("dontshowagain", true);
- editor.commit();
- }
- dialog.dismiss();
- }
- });
- ll.addView(b3);
-
- dialog.setContentView(ll);
- dialog.show();
- }
+package org.fox.ttrss.util; + +// From http://androidsnippets.com/prompt-engaged-users-to-rate-your-app-in-the-android-market-appirater + +import android.app.Dialog; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.net.Uri; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.TextView; + +public class AppRater { + private final static String APP_TITLE = "Tiny Tiny RSS"; + private final static String APP_PNAME = "org.fox.ttrss"; + + private final static int DAYS_UNTIL_PROMPT = 3; + private final static int LAUNCHES_UNTIL_PROMPT = 7; + + public static void appLaunched(Context mContext) { + SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0); + + if (prefs.getBoolean("dontshowagain", false)) { return ; } + + SharedPreferences.Editor editor = prefs.edit(); + + // Increment launch counter + long launch_count = prefs.getLong("launch_count", 0) + 1; + editor.putLong("launch_count", launch_count); + + // Get date of first launch + Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0); + if (date_firstLaunch == 0) { + date_firstLaunch = System.currentTimeMillis(); + editor.putLong("date_firstlaunch", date_firstLaunch); + } + + // Wait at least n days before opening + if (launch_count >= LAUNCHES_UNTIL_PROMPT && + !prefs.getBoolean("dontshowagain", false) && + System.currentTimeMillis() >= date_firstLaunch + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) { + + showRateDialog(mContext, editor); + } + + editor.commit(); + } + + public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) { + final Dialog dialog = new Dialog(mContext); + dialog.setTitle("Rate " + APP_TITLE); + + LinearLayout ll = new LinearLayout(mContext); + ll.setOrientation(LinearLayout.VERTICAL); + + TextView tv = new TextView(mContext); + tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!"); + tv.setWidth(240); + tv.setPadding(4, 0, 4, 10); + ll.addView(tv); + + Button b1 = new Button(mContext); + b1.setText("Rate " + APP_TITLE); + b1.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + try { + mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME))); + } catch (ActivityNotFoundException e) { + mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + APP_PNAME))); + } + dialog.dismiss(); + } + }); + ll.addView(b1); + + Button b2 = new Button(mContext); + b2.setText("Remind me later"); + b2.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + dialog.dismiss(); + } + }); + ll.addView(b2); + + Button b3 = new Button(mContext); + b3.setText("No, thanks"); + b3.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + if (editor != null) { + editor.putBoolean("dontshowagain", true); + editor.commit(); + } + dialog.dismiss(); + } + }); + ll.addView(b3); + + dialog.setContentView(ll); + dialog.show(); + } }
\ No newline at end of file diff --git a/src/org/fox/ttrss/util/DatabaseHelper.java b/src/org/fox/ttrss/util/DatabaseHelper.java index 501aadd1..cf5380e0 100644 --- a/src/org/fox/ttrss/util/DatabaseHelper.java +++ b/src/org/fox/ttrss/util/DatabaseHelper.java @@ -1,86 +1,86 @@ -package org.fox.ttrss.util;
-import android.content.Context;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteOpenHelper;
-import android.provider.BaseColumns;
-
-
-public class DatabaseHelper extends SQLiteOpenHelper {
-
- @SuppressWarnings("unused")
- private final String TAG = this.getClass().getSimpleName();
- public static final String DATABASE_NAME = "OfflineStorage.db";
- public static final int DATABASE_VERSION = 3;
-
- public DatabaseHelper(Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
- db.execSQL("DROP TABLE IF EXISTS categories;");
- db.execSQL("DROP TABLE IF EXISTS feeds;");
- db.execSQL("DROP TABLE IF EXISTS articles;");
- db.execSQL("DROP VIEW IF EXISTS feeds_unread;");
- db.execSQL("DROP TRIGGER IF EXISTS articles_set_modified;");
-
- db.execSQL("CREATE TABLE IF NOT EXISTS feeds (" +
- BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
- "feed_url TEXT, " +
- "title TEXT, " +
- "has_icon BOOLEAN, " +
- "cat_id INTEGER" +
- ");");
-
- db.execSQL("CREATE TABLE IF NOT EXISTS categories (" +
- BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
- "title TEXT" +
- ");");
-
- db.execSQL("CREATE TABLE IF NOT EXISTS articles (" +
- BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
- "unread BOOLEAN, " +
- "marked BOOLEAN, " +
- "published BOOLEAN, " +
- "updated INTEGER, " +
- "is_updated BOOLEAN, " +
- "title TEXT, " +
- "link TEXT, " +
- "feed_id INTEGER, " +
- "tags TEXT, " +
- "content TEXT, " +
- "selected BOOLEAN, " +
- "modified BOOLEAN" +
- ");");
-
- db.execSQL("CREATE TRIGGER articles_set_modified UPDATE OF marked, published, unread ON articles " +
- "BEGIN " +
- " UPDATE articles SET modified = 1 WHERE " + BaseColumns._ID + " = " + "OLD." + BaseColumns._ID + "; " +
- "END;");
-
- db.execSQL("CREATE VIEW feeds_unread AS SELECT feeds."+BaseColumns._ID+" AS "+BaseColumns._ID+", " +
- "feeds.title AS title, " +
- "cat_id, " +
- "SUM(articles.unread) AS unread FROM feeds " +
- "LEFT JOIN articles ON (articles.feed_id = feeds."+BaseColumns._ID+") " +
- "GROUP BY feeds."+BaseColumns._ID+", feeds.title;");
-
- //sqlite> select categories._id,categories.title,sum(articles.unread) from categories left j
- //oin feeds on (feeds.cat_id = categories._id) left join articles on (articles.feed_id = fee
- //ds._id) group by categories._id;
-
- db.execSQL("CREATE VIEW cats_unread AS SELECT categories."+BaseColumns._ID+" AS "+BaseColumns._ID+", " +
- "categories.title AS title, " +
- "SUM(articles.unread) AS unread FROM categories " +
- "LEFT JOIN feeds ON (feeds.cat_id = categories."+BaseColumns._ID+") "+
- "LEFT JOIN articles ON (articles.feed_id = feeds."+BaseColumns._ID+") " +
- "GROUP BY categories."+BaseColumns._ID+", categories.title;");
-
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- onCreate(db);
- }
-
-}
+package org.fox.ttrss.util; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.provider.BaseColumns; + + +public class DatabaseHelper extends SQLiteOpenHelper { + + @SuppressWarnings("unused") + private final String TAG = this.getClass().getSimpleName(); + public static final String DATABASE_NAME = "OfflineStorage.db"; + public static final int DATABASE_VERSION = 3; + + public DatabaseHelper(Context context) { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + } + + @Override + public void onCreate(SQLiteDatabase db) { + db.execSQL("DROP TABLE IF EXISTS categories;"); + db.execSQL("DROP TABLE IF EXISTS feeds;"); + db.execSQL("DROP TABLE IF EXISTS articles;"); + db.execSQL("DROP VIEW IF EXISTS feeds_unread;"); + db.execSQL("DROP TRIGGER IF EXISTS articles_set_modified;"); + + db.execSQL("CREATE TABLE IF NOT EXISTS feeds (" + + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + + "feed_url TEXT, " + + "title TEXT, " + + "has_icon BOOLEAN, " + + "cat_id INTEGER" + + ");"); + + db.execSQL("CREATE TABLE IF NOT EXISTS categories (" + + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + + "title TEXT" + + ");"); + + db.execSQL("CREATE TABLE IF NOT EXISTS articles (" + + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + + "unread BOOLEAN, " + + "marked BOOLEAN, " + + "published BOOLEAN, " + + "updated INTEGER, " + + "is_updated BOOLEAN, " + + "title TEXT, " + + "link TEXT, " + + "feed_id INTEGER, " + + "tags TEXT, " + + "content TEXT, " + + "selected BOOLEAN, " + + "modified BOOLEAN" + + ");"); + + db.execSQL("CREATE TRIGGER articles_set_modified UPDATE OF marked, published, unread ON articles " + + "BEGIN " + + " UPDATE articles SET modified = 1 WHERE " + BaseColumns._ID + " = " + "OLD." + BaseColumns._ID + "; " + + "END;"); + + db.execSQL("CREATE VIEW feeds_unread AS SELECT feeds."+BaseColumns._ID+" AS "+BaseColumns._ID+", " + + "feeds.title AS title, " + + "cat_id, " + + "SUM(articles.unread) AS unread FROM feeds " + + "LEFT JOIN articles ON (articles.feed_id = feeds."+BaseColumns._ID+") " + + "GROUP BY feeds."+BaseColumns._ID+", feeds.title;"); + + //sqlite> select categories._id,categories.title,sum(articles.unread) from categories left j + //oin feeds on (feeds.cat_id = categories._id) left join articles on (articles.feed_id = fee + //ds._id) group by categories._id; + + db.execSQL("CREATE VIEW cats_unread AS SELECT categories."+BaseColumns._ID+" AS "+BaseColumns._ID+", " + + "categories.title AS title, " + + "SUM(articles.unread) AS unread FROM categories " + + "LEFT JOIN feeds ON (feeds.cat_id = categories."+BaseColumns._ID+") "+ + "LEFT JOIN articles ON (articles.feed_id = feeds."+BaseColumns._ID+") " + + "GROUP BY categories."+BaseColumns._ID+", categories.title;"); + + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + onCreate(db); + } + +} diff --git a/src/org/fox/ttrss/util/HeadlinesRequest.java b/src/org/fox/ttrss/util/HeadlinesRequest.java index ca76887f..9ad5ef91 100644 --- a/src/org/fox/ttrss/util/HeadlinesRequest.java +++ b/src/org/fox/ttrss/util/HeadlinesRequest.java @@ -1,83 +1,83 @@ -package org.fox.ttrss.util;
-
-import java.lang.reflect.Type;
-import java.util.List;
-
-import org.fox.ttrss.ApiRequest;
-import org.fox.ttrss.GlobalState;
-import org.fox.ttrss.OnlineActivity;
-import org.fox.ttrss.R;
-import org.fox.ttrss.types.Article;
-import org.fox.ttrss.types.ArticleList;
-
-import android.content.Context;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.reflect.TypeToken;
-
-public class HeadlinesRequest extends ApiRequest {
- public static final int HEADLINES_REQUEST_SIZE = 30;
- public static final int HEADLINES_BUFFER_MAX = 1500;
-
- private int m_offset = 0;
- private OnlineActivity m_activity;
- private ArticleList m_articles = GlobalState.getInstance().m_loadedArticles;
-
- public HeadlinesRequest(Context context, OnlineActivity activity) {
- super(context);
-
- m_activity = activity;
- }
-
- protected void onPostExecute(JsonElement result) {
- if (result != null) {
- try {
- JsonArray content = result.getAsJsonArray();
- if (content != null) {
- Type listType = new TypeToken<List<Article>>() {}.getType();
- final List<Article> articles = new Gson().fromJson(content, listType);
-
- while (m_articles.size() > HEADLINES_BUFFER_MAX)
- m_articles.remove(0);
-
- if (m_offset == 0)
- m_articles.clear();
- else
- if (m_articles.get(m_articles.size()-1).id == -1)
- m_articles.remove(m_articles.size()-1); // remove previous placeholder
-
- for (Article f : articles)
- m_articles.add(f);
-
- if (articles.size() == HEADLINES_REQUEST_SIZE) {
- Article placeholder = new Article(-1);
- m_articles.add(placeholder);
- }
-
- /* if (m_articles.size() == 0)
- m_activity.setLoadingStatus(R.string.no_headlines_to_display, false);
- else */
-
- m_activity.setLoadingStatus(R.string.blank, false);
-
- return;
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- if (m_lastError == ApiError.LOGIN_FAILED) {
- m_activity.login();
- } else {
- m_activity.setLoadingStatus(getErrorMessage(), false);
- }
- }
-
- public void setOffset(int skip) {
- m_offset = skip;
- }
-}
+package org.fox.ttrss.util; + +import java.lang.reflect.Type; +import java.util.List; + +import org.fox.ttrss.ApiRequest; +import org.fox.ttrss.GlobalState; +import org.fox.ttrss.OnlineActivity; +import org.fox.ttrss.R; +import org.fox.ttrss.types.Article; +import org.fox.ttrss.types.ArticleList; + +import android.content.Context; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; + +public class HeadlinesRequest extends ApiRequest { + public static final int HEADLINES_REQUEST_SIZE = 30; + public static final int HEADLINES_BUFFER_MAX = 1500; + + private int m_offset = 0; + private OnlineActivity m_activity; + private ArticleList m_articles = GlobalState.getInstance().m_loadedArticles; + + public HeadlinesRequest(Context context, OnlineActivity activity) { + super(context); + + m_activity = activity; + } + + protected void onPostExecute(JsonElement result) { + if (result != null) { + try { + JsonArray content = result.getAsJsonArray(); + if (content != null) { + Type listType = new TypeToken<List<Article>>() {}.getType(); + final List<Article> articles = new Gson().fromJson(content, listType); + + while (m_articles.size() > HEADLINES_BUFFER_MAX) + m_articles.remove(0); + + if (m_offset == 0) + m_articles.clear(); + else + if (m_articles.get(m_articles.size()-1).id == -1) + m_articles.remove(m_articles.size()-1); // remove previous placeholder + + for (Article f : articles) + m_articles.add(f); + + if (articles.size() == HEADLINES_REQUEST_SIZE) { + Article placeholder = new Article(-1); + m_articles.add(placeholder); + } + + /* if (m_articles.size() == 0) + m_activity.setLoadingStatus(R.string.no_headlines_to_display, false); + else */ + + m_activity.setLoadingStatus(R.string.blank, false); + + return; + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + if (m_lastError == ApiError.LOGIN_FAILED) { + m_activity.login(); + } else { + m_activity.setLoadingStatus(getErrorMessage(), false); + } + } + + public void setOffset(int skip) { + m_offset = skip; + } +} diff --git a/src/org/fox/ttrss/util/ImageCacheService.java b/src/org/fox/ttrss/util/ImageCacheService.java index 96342d60..8bd4840c 100644 --- a/src/org/fox/ttrss/util/ImageCacheService.java +++ b/src/org/fox/ttrss/util/ImageCacheService.java @@ -1,211 +1,211 @@ -package org.fox.ttrss.util;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Date;
-
-import org.fox.ttrss.OnlineActivity;
-import org.fox.ttrss.R;
-import org.fox.ttrss.offline.OfflineDownloadService;
-
-import android.app.ActivityManager;
-import android.app.ActivityManager.RunningServiceInfo;
-import android.app.IntentService;
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Environment;
-
-public class ImageCacheService extends IntentService {
-
- @SuppressWarnings("unused")
- private final String TAG = this.getClass().getSimpleName();
-
- public static final int NOTIFY_DOWNLOADING = 1;
-
- private static final String CACHE_PATH = "/image-cache/";
-
- private int m_imagesDownloaded = 0;
-
- private NotificationManager m_nmgr;
-
- public ImageCacheService() {
- super("ImageCacheService");
- }
-
- private boolean isDownloadServiceRunning() {
- ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
- for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
- if ("org.fox.ttrss.OfflineDownloadService".equals(service.service.getClassName())) {
- return true;
- }
- }
- return false;
- }
-
-
- @Override
- public void onCreate() {
- super.onCreate();
- m_nmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
- }
-
- public static boolean isUrlCached(Context context, String url) {
- String hashedUrl = md5(url);
-
- File storage = context.getExternalCacheDir();
-
- File file = new File(storage.getAbsolutePath() + CACHE_PATH + "/" + hashedUrl + ".png");
-
- return file.exists();
- }
-
- public static String getCacheFileName(Context context, String url) {
- String hashedUrl = md5(url);
-
- File storage = context.getExternalCacheDir();
-
- File file = new File(storage.getAbsolutePath() + CACHE_PATH + "/" + hashedUrl + ".png");
-
- return file.getAbsolutePath();
- }
-
- public static void cleanupCache(Context context, boolean deleteAll) {
- if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
- File storage = context.getExternalCacheDir();
- File cachePath = new File(storage.getAbsolutePath() + CACHE_PATH);
-
- long now = new Date().getTime();
-
- if (cachePath.isDirectory()) {
- for (File file : cachePath.listFiles()) {
- if (deleteAll || now - file.lastModified() > 1000*60*60*24*7) {
- file.delete();
- }
- }
- }
- }
- }
-
- protected static String md5(String s) {
- try {
- MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
- digest.update(s.getBytes());
- byte messageDigest[] = digest.digest();
-
- StringBuffer hexString = new StringBuffer();
- for (int i=0; i<messageDigest.length; i++)
- hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
-
- return hexString.toString();
-
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
-
- return null;
- }
-
- private InputStream getStream(String urlString) {
- try {
- URL url = new URL(urlString);
- URLConnection urlConnection = url.openConnection();
- urlConnection.setConnectTimeout(250);
- return urlConnection.getInputStream();
- } catch (Exception ex) {
- return null;
- }
- }
-
- @SuppressWarnings("deprecation")
- private void updateNotification(String msg) {
- Notification notification = new Notification(R.drawable.icon,
- getString(R.string.notify_downloading_title), System.currentTimeMillis());
-
- PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
- new Intent(this, OnlineActivity.class), 0);
-
- notification.flags |= Notification.FLAG_ONGOING_EVENT;
- notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
-
- notification.setLatestEventInfo(this, getString(R.string.notify_downloading_title), msg, contentIntent);
-
- m_nmgr.notify(NOTIFY_DOWNLOADING, notification);
- }
-
- /* private void updateNotification(int msgResId) {
- updateNotification(getString(msgResId));
- } */
-
- @Override
- protected void onHandleIntent(Intent intent) {
- String url = intent.getStringExtra("url");
-
- //Log.d(TAG, "got request to download URL=" + url);
-
- if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
- return;
-
- String hashedUrl = md5(url);
-
- File storage = getExternalCacheDir();
- File cachePath = new File(storage.getAbsolutePath() + CACHE_PATH);
- if (!cachePath.exists()) cachePath.mkdirs();
-
- if (cachePath.isDirectory() && hashedUrl != null) {
- File outputFile = new File(cachePath.getAbsolutePath() + "/" + hashedUrl + ".png");
-
- if (!outputFile.exists()) {
-
- //Log.d(TAG, "downloading to " + outputFile.getAbsolutePath());
-
- InputStream is = getStream(url);
-
- if (is != null) {
- try {
- FileOutputStream fos = new FileOutputStream(outputFile);
-
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = is.read(buffer)) != -1) {
- fos.write(buffer, 0, len);
- }
-
- fos.close();
- is.close();
-
- m_imagesDownloaded++;
-
- updateNotification(getString(R.string.notify_downloading_images, m_imagesDownloaded));
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
-
- @Override
- public void onDestroy() {
- super.onDestroy();
-
- if (!isDownloadServiceRunning()) {
- m_nmgr.cancel(NOTIFY_DOWNLOADING);
-
- Intent success = new Intent();
- success.setAction(OfflineDownloadService.INTENT_ACTION_SUCCESS);
- success.addCategory(Intent.CATEGORY_DEFAULT);
- sendBroadcast(success);
- }
- }
-
-}
+package org.fox.ttrss.util; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Date; + +import org.fox.ttrss.OnlineActivity; +import org.fox.ttrss.R; +import org.fox.ttrss.offline.OfflineDownloadService; + +import android.app.ActivityManager; +import android.app.ActivityManager.RunningServiceInfo; +import android.app.IntentService; +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.Environment; + +public class ImageCacheService extends IntentService { + + @SuppressWarnings("unused") + private final String TAG = this.getClass().getSimpleName(); + + public static final int NOTIFY_DOWNLOADING = 1; + + private static final String CACHE_PATH = "/image-cache/"; + + private int m_imagesDownloaded = 0; + + private NotificationManager m_nmgr; + + public ImageCacheService() { + super("ImageCacheService"); + } + + private boolean isDownloadServiceRunning() { + ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); + for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if ("org.fox.ttrss.OfflineDownloadService".equals(service.service.getClassName())) { + return true; + } + } + return false; + } + + + @Override + public void onCreate() { + super.onCreate(); + m_nmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); + } + + public static boolean isUrlCached(Context context, String url) { + String hashedUrl = md5(url); + + File storage = context.getExternalCacheDir(); + + File file = new File(storage.getAbsolutePath() + CACHE_PATH + "/" + hashedUrl + ".png"); + + return file.exists(); + } + + public static String getCacheFileName(Context context, String url) { + String hashedUrl = md5(url); + + File storage = context.getExternalCacheDir(); + + File file = new File(storage.getAbsolutePath() + CACHE_PATH + "/" + hashedUrl + ".png"); + + return file.getAbsolutePath(); + } + + public static void cleanupCache(Context context, boolean deleteAll) { + if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { + File storage = context.getExternalCacheDir(); + File cachePath = new File(storage.getAbsolutePath() + CACHE_PATH); + + long now = new Date().getTime(); + + if (cachePath.isDirectory()) { + for (File file : cachePath.listFiles()) { + if (deleteAll || now - file.lastModified() > 1000*60*60*24*7) { + file.delete(); + } + } + } + } + } + + protected static String md5(String s) { + try { + MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); + digest.update(s.getBytes()); + byte messageDigest[] = digest.digest(); + + StringBuffer hexString = new StringBuffer(); + for (int i=0; i<messageDigest.length; i++) + hexString.append(Integer.toHexString(0xFF & messageDigest[i])); + + return hexString.toString(); + + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + + return null; + } + + private InputStream getStream(String urlString) { + try { + URL url = new URL(urlString); + URLConnection urlConnection = url.openConnection(); + urlConnection.setConnectTimeout(250); + return urlConnection.getInputStream(); + } catch (Exception ex) { + return null; + } + } + + @SuppressWarnings("deprecation") + private void updateNotification(String msg) { + Notification notification = new Notification(R.drawable.icon, + getString(R.string.notify_downloading_title), System.currentTimeMillis()); + + PendingIntent contentIntent = PendingIntent.getActivity(this, 0, + new Intent(this, OnlineActivity.class), 0); + + notification.flags |= Notification.FLAG_ONGOING_EVENT; + notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE; + + notification.setLatestEventInfo(this, getString(R.string.notify_downloading_title), msg, contentIntent); + + m_nmgr.notify(NOTIFY_DOWNLOADING, notification); + } + + /* private void updateNotification(int msgResId) { + updateNotification(getString(msgResId)); + } */ + + @Override + protected void onHandleIntent(Intent intent) { + String url = intent.getStringExtra("url"); + + //Log.d(TAG, "got request to download URL=" + url); + + if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) + return; + + String hashedUrl = md5(url); + + File storage = getExternalCacheDir(); + File cachePath = new File(storage.getAbsolutePath() + CACHE_PATH); + if (!cachePath.exists()) cachePath.mkdirs(); + + if (cachePath.isDirectory() && hashedUrl != null) { + File outputFile = new File(cachePath.getAbsolutePath() + "/" + hashedUrl + ".png"); + + if (!outputFile.exists()) { + + //Log.d(TAG, "downloading to " + outputFile.getAbsolutePath()); + + InputStream is = getStream(url); + + if (is != null) { + try { + FileOutputStream fos = new FileOutputStream(outputFile); + + byte[] buffer = new byte[1024]; + int len = 0; + while ((len = is.read(buffer)) != -1) { + fos.write(buffer, 0, len); + } + + fos.close(); + is.close(); + + m_imagesDownloaded++; + + updateNotification(getString(R.string.notify_downloading_images, m_imagesDownloaded)); + + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + + @Override + public void onDestroy() { + super.onDestroy(); + + if (!isDownloadServiceRunning()) { + m_nmgr.cancel(NOTIFY_DOWNLOADING); + + Intent success = new Intent(); + success.setAction(OfflineDownloadService.INTENT_ACTION_SUCCESS); + success.addCategory(Intent.CATEGORY_DEFAULT); + sendBroadcast(success); + } + } + +} diff --git a/src/org/fox/ttrss/util/PrefsBackupAgent.java b/src/org/fox/ttrss/util/PrefsBackupAgent.java index a786be56..2b33615f 100644 --- a/src/org/fox/ttrss/util/PrefsBackupAgent.java +++ b/src/org/fox/ttrss/util/PrefsBackupAgent.java @@ -1,19 +1,19 @@ -package org.fox.ttrss.util;
-
-import android.app.backup.BackupAgentHelper;
-import android.app.backup.SharedPreferencesBackupHelper;
-
-public class PrefsBackupAgent extends BackupAgentHelper {
- // The name of the SharedPreferences file
- static final String PREFS = "org.fox.ttrss_preferences";
-
- // A key to uniquely identify the set of backup data
- static final String PREFS_BACKUP_KEY = "prefs";
-
- // Allocate a helper and add it to the backup agent
- @Override
- public void onCreate() {
- SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
- addHelper(PREFS_BACKUP_KEY, helper);
- }
-}
+package org.fox.ttrss.util; + +import android.app.backup.BackupAgentHelper; +import android.app.backup.SharedPreferencesBackupHelper; + +public class PrefsBackupAgent extends BackupAgentHelper { + // The name of the SharedPreferences file + static final String PREFS = "org.fox.ttrss_preferences"; + + // A key to uniquely identify the set of backup data + static final String PREFS_BACKUP_KEY = "prefs"; + + // Allocate a helper and add it to the backup agent + @Override + public void onCreate() { + SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS); + addHelper(PREFS_BACKUP_KEY, helper); + } +} |