Home > Android, Bruce's Posts, Java > Fortune Files

Fortune Files

Creating a quote of the day application requires quotes. So where does one go to get a lots of free quotes that are actually interesting. One place is a fortune file.

A fortune file contains a set of quotes similar to those found in a fortune cookie. Fortune files comprise the underlying database of the fortune program which appeared over 30 years with the release of Version 7 UNIX.

Since then creating and publishing fortune files has become a cottage industry. A quick search of the web will turn up numerous fortune files reflecting a wide variety genres. I download one from here. I contains over 9000 quotes. Next, how to incorporate it into my application?

The first step invokes preparing the fortune file for quick random lookup. A fortune file is a text file. Each line in the file contains a unique quote.

Rocks might teach us life's secrets, were it not for the language barrier.
Romance addiction is an invention of Western culture. — Anne Schaeff

The quote of the day widgets will random choose one of the quotes from the fortune file each day. This adds the following application requirements:

  • The widgets and activity need a common way to get the current day’s quote.
  • Each day the widgets need to be updated with new quotes.

An Android Service will provide an method to get quotes.

QuoteService extends IntentService. 

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This “work queue processor” pattern is commonly used to offload tasks from an application’s main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread — they may take as long as necessary (and will not block the application’s main loop), but only one request will be processed at a time.

The initial version of QuoteService reads the Fortune file that’s been packaged as a raw resource and caches the quotes in an array. Not a great final solution but sufficient for now.

QuoteService.java

public class QuoteService extends IntentService {
	static private String TAG = QuoteService.class.getSimpleName();

	private final IBinder binder = new QuoteBinder();

	public class QuoteBinder extends Binder {
		public QuoteService getService() {
            	return QuoteService.this;
		}
	}

	private final Random random = new Random();

	private String[] quotes = { "Never put off until tomorrow what you can do the day after tomorrow. -- Mark Twain" };

	public String[] getQuotes() {
		return quotes;
	}

	public void setQuotes(String[] quotes) {
		this.quotes = quotes;
	}

	public String getQuote(int index) {
		return quotes != null ? quotes[index] : null;
	}

	public String qetRandomQuote() {
		return getQuote(random.nextInt(quotes.length));
	}

	public QuoteService() {
		super(TAG);
		Log.d(TAG, String.format("QuoteService"));
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.d(TAG, String.format("onBind - intent: %s", intent));
		return binder;
	}

	@Override
	public void onCreate() {
		Log.d(TAG, String.format("onCreate"));

		InputStream inputStream = this.getResources().openRawResource(R.raw.fortunes);
		Reader reader = new InputStreamReader(inputStream);
		BufferedReader in = new BufferedReader(reader);

		List<String> list = new ArrayList<String>();
		try {
			String string;

			while ((string = in.readLine()) != null) {
				Log.d(TAG, String.format("string: %s", string));
				list.add(string);
			}
			in.close();
		} catch (IOException e) {
		}

		quotes = list.toArray(new String[list.size()]);
		Log.d(TAG, String.format("quotes read: %d", quotes.length));
	}

	@Override
	public void onDestroy() {
		Log.d(TAG, String.format("onDestroy"));
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Log.d(TAG, String.format("onHandleIntent - intent: %s", intent));
	}
}

When QuoteActivity starts it binds to QuoteService. When the asynchronous connection to the service is made QuoteActivity’s views are then be updated if currently empty. If QuoteActivity is started with an Intent that contains a quote then that quote will be display. This allows QuoteActivity to be launched from a widget. The widget’s quote is passed along. Right now QuoteActivity just reproduces the quote. Later it will display more more information related to that quote.

QuoteActivity.java

public class QuoteActivity extends Activity {
	static private String TAG = QuoteActivity.class.getSimpleName();
	static public String QUOTE = "org.bwgz.qotd.activity.QuoteActivity.QUOTE";

	private QuoteService service;
	private String quote;
	private boolean connected = false;

	public boolean isConnected() {
		return connected;
	}

	public void setConnected(boolean connected) {
		this.connected = connected;
	}

	public String getQuote() {
		return quote;
	}

	public QuoteService getService() {
		return service;
	}

	public void setService(QuoteService service) {
		this.service = service;
	}

	public void setQuote(String quote) {
		this.quote = quote;

    		TextView textView = (TextView)findViewById(R.id.quote);
    		textView.setText(quote);
	}

	private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder binder) {
    		Log.d(TAG, String.format("onServiceConnected - className: %s  service: %s", className, binder));

            setConnected(true);
            setService(((QuoteBinder) binder).getService());

            if (getQuote() == null) {
            	setQuote(getService().qetRandomQuote());
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
    		Log.d(TAG, String.format("onServiceDisconnected - name: %s", name));

            setConnected(false);
        }
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, String.format("onCreate - savedInstanceState: %s", savedInstanceState));

        	setContentView(R.layout.activity_quote);
	}

    @Override
    protected void onStart() {
        super.onStart();
		Log.d(TAG, String.format("onStart"));

        bindService(new Intent(this, QuoteService.class), connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onResume() {
	super.onResume();
	Log.d(TAG, String.format("onResume"));

	Intent intent = getIntent();
	String quote = intent.getStringExtra(QUOTE);
	Log.d(TAG, String.format("intent: %s  quote: %s", intent, quote));

	if (quote != null) {
		setQuote(quote);
	}
    }

    @Override
    protected void onPause() {
	super.onPause();
	Log.d(TAG, String.format("onPause"));
    }

    @Override
    protected void onStop() {
	super.onStop();
	Log.d(TAG, String.format("onStop"));

	if (isConnected()) {
            unbindService(connection);
            setConnected(false);
        }
    }

    @Override
    protected void onDestroy() {
	super.onDestroy();
	Log.d(TAG, String.format("onDestroy"));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	MenuInflater inflater = getMenuInflater();
	inflater.inflate(R.menu.options, menu);
	return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	if (item.getItemId() == android.R.id.home || item.getItemId() == 0) {
            return false;
	}
	if (item.getItemId() == R.id.developer) {
    	    Intent intent = new Intent(this, DeveloperActivity.class);
    	    startActivity(intent);
    	}

	return true;
    }
}

Things aren’t were a little more complicated with QuoteWidgetProvider. Android does not allow a BroadcastReceiver to bind to a Service.

Because AppWidgetProvider is an extension of BroadcastReceiver, your process is not guaranteed to keep running after the callback methods return (see BroadcastReceiver for information about the broadcast lifecycle). If your App Widget setup process can take several seconds (perhaps while performing web requests) and you require that your process continues, consider starting a Service in the onUpdate()method. From within the Service, you can perform your own updates to the App Widget without worrying about the AppWidgetProvider closing down due to an Application Not Responding (ANR) error.

I created QuoteOfTheDayService to act as a proxy for QuoteWidgetProvider. QuoteOfTheDayService does a few things:

  • It binds to QuoteService so that it can access the quotes.
  • It ensures all the widgets have a random quote.
  • Using a custom Handler it refreshes all the widgets with new random quotes when the current day rolls over.

QuoteOfTheDayService.java

public class QuoteOfTheDayService extends IntentService {
	static private String TAG = QuoteOfTheDayService.class.getSimpleName();
	static public String APP_WIDGET_IDS = "org.bwgz.qotd.service.QuoteOfTheDayService.APP_WIDGET_IDS";

        private QuoteService quoteService;
	private boolean connected = false;

	public QuoteService getQuoteService() {
		return quoteService;
	}

	public void setQuoteService(QuoteService quoteService) {
		this.quoteService = quoteService;
	}

        public boolean isConnected() {
		return connected;
	}

	public void setConnected(boolean connected) {
		this.connected = connected;
	}

	static private class AlarmHandler extends Handler {
    	private QuoteOfTheDayService qotdService;

		public AlarmHandler(QuoteOfTheDayService service) {
    		this.qotdService = service;
    	}

        @Override
        public void handleMessage(Message msg) {
            ComponentName widget = new ComponentName(qotdService, QuoteWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(qotdService);

            qotdService.updateAppWidgets(manager.getAppWidgetIds(widget));
            qotdService.setAlarm();
        }
    }

    private AlarmHandler handler = new AlarmHandler(this);

	private long getTest() {
		Calendar calendar = GregorianCalendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);

		calendar = new GregorianCalendar(year, month, day, hour, minute + 1, second);
		Log.d(TAG, String.format("next: %s", calendar));

		return calendar.getTimeInMillis();
	}

	@SuppressWarnings("unused")
	private long getMidnight() {
		Calendar calendar = GregorianCalendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);

		calendar = new GregorianCalendar(year, month, day);
		Log.d(TAG, String.format("today: %s", calendar));
		calendar.roll(Calendar.DATE, true);
		Log.d(TAG, String.format("tomorrow: %s", calendar));

		return calendar.getTimeInMillis();
	}

	public void setAlarm() {
		long next = getTest();
		long now = System.currentTimeMillis();
		long delta = next - now;
		Log.d(TAG, String.format(" next: %d", next));
		Log.d(TAG, String.format("  now: %d", now));
		Log.d(TAG, String.format("delta: %d", delta));

		handler.sendMessageDelayed(handler.obtainMessage(), delta);
	}

	private ServiceConnection connection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder binder) {
    		Log.d(TAG, String.format("onServiceConnected - name: %s  binder: %s", name, binder));

    		setConnected(true);

    		setQuoteService(((QuoteBinder) binder).getService());
    		Log.d(TAG, String.format("service: %s", getQuoteService()));

                ComponentName widget = new ComponentName(QuoteOfTheDayService.this, QuoteWidgetProvider.class);
                AppWidgetManager manager = AppWidgetManager.getInstance(QuoteOfTheDayService.this);

    		updateAppWidgets(manager.getAppWidgetIds(widget));
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
    		Log.d(TAG, String.format("onServiceDisconnected - name: %s", name));

    		setConnected(false);
		}
    };

	public QuoteOfTheDayService() {
		super(TAG);
	}

	private void updateAppWidgets(int[] appWidgetIds) {
		Log.d(TAG, String.format("updateWidgets - appWidgetIds: %s", appWidgetIds));

		if (appWidgetIds!= null) {
	        for (int appWidgetId : appWidgetIds) {
	    		Log.d(TAG, String.format("widgetId: %s", appWidgetId));
	    		String quote = getQuoteService() != null ? getQuoteService().qetRandomQuote() : new String();

	        	RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget_quote);
	        	remoteViews.setTextViewText(R.id.quote, quote);

	        	Intent intent = new Intent(this, QuoteActivity.class);
	        	intent.putExtra(QuoteActivity.QUOTE, quote);
	                PendingIntent pendingIntent = PendingIntent.getActivity(this, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT);

	        	remoteViews.setOnClickPendingIntent(R.id.widget, pendingIntent);

	                AppWidgetManager manager = AppWidgetManager.getInstance(QuoteOfTheDayService.this);
	        	manager.updateAppWidget(appWidgetId, remoteViews);
	        }
		}
	}

	@Override
	public void onCreate() {
		Log.d(TAG, String.format("onCreate"));

		bindService(new Intent(this, QuoteService.class), connection, Context.BIND_AUTO_CREATE);
		setAlarm();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, String.format("onStartCommand - intent: %s  flags: %d  startId: %d", intent, flags, startId));

		int[] appWidgetIds = intent.getIntArrayExtra(APP_WIDGET_IDS);
		updateAppWidgets(appWidgetIds);

		return Service.START_NOT_STICKY;
	}

	@Override
	public void onDestroy() {
            Log.d(TAG, String.format("onDestroy"));

            if (isConnected()) {
                unbindService(connection);
                setConnected(false);
            }
	}

	@Override
	protected void onHandleIntent(Intent intent) {
	}

}

There were a few tricky bits. One was getting each widget to pass along its quote when clicked. I keep getting all the widgets pass the quote of the last widget in the list. Even though all the widgets has a different quote they same quote was passed with the Intent. The important parts was …

PendingIntent pendingIntent = PendingIntent.getActivity(this, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT);

The documentation states …

public static PendingIntent getActivity (Context context, int requestCode, Intent intent, int flags, Bundle options)

requestCode Private request code for the sender (currently not used).

In fact you can specify the widget id in the requestCode parameter.

When QuoteWidgetProvider starts QuoteOfTheDayService  it passes the id’s of the widgets needing updating.  Here’s what it looks link now.

QuoteWidgetProvider.java

 public class QuoteWidgetProvider extends AppWidgetProvider {
     static private String TAG = QuoteWidgetProvider.class.getSimpleName();

     @Override
     public void onEnabled(Context context) {
         Log.d(TAG, String.format("onEnabled  - context %s", context));
     }

     @Override
     public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
         Log.d(TAG, String.format("onUpdate - context %s  appWidgetManager: %s  appWidgetIds: %s", context, appWidgetManager, appWidgetIds));

Intent intent = new Intent(context, QuoteOfTheDayService.class);
         intent.putExtra(QuoteOfTheDayService.APP_WIDGET_IDS, appWidgetIds);
         context.startService(intent);
     }

     @Override
     public void onDeleted(Context context, int[] appWidgetIds) {
         Log.d(TAG, String.format("onDeleted - context %s  appWidgetIds: %s", context, appWidgetIds));
     }

     @Override
     public void onDisabled (Context context) {
         Log.d(TAG, String.format("onDisabled   - context %s", context));

         context.stopService(new Intent(context, QuoteOfTheDayService.class));
     }
 }
 

The code is available at GitHub.

Advertisements
Categories: Android, Bruce's Posts, Java
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: