Ruboto: Android apps in Ruby
The JRuby of lesson 94 runs wherever Java runs – and Android apps are Java programs (or Kotlin ones, which is the same to the phone). Ruboto packs JRuby into an Android app: its screens are written in Ruby, and Ruby calls Android's Java classes as it called java.util.ArrayList. This lesson runs Ruboto 2, a new version that builds with today's Android tools and JRuby 10.
A browser has no Android. So this lesson brings a simulated phone: the JRuby of lesson 94, plus stand-ins for the Android classes apps use most – Activity, TextView, Button, Toast, Handler … –, written in Java and compiled into it, and Ruboto's own Ruby files, unchanged. The phone below a cell is drawn by the page; what the app does is JRuby's. Nothing else loads: JRuby is the same 7 MB as in lesson 94, cached after the first time, and the phone adds 0.3 MB of photos.
Ask the phone what it is:
[android.os.Build::MODEL, android.os.Build::VERSION::RELEASE, android.os.Build::VERSION::SDK_INT]
android.os.Build is a Java class with constants; VERSION is a class inside it, hence the second ::. A real phone names its model here. API level 34 is Android 14 – Ruboto 2 runs on Android 13 and newer, and down to Android 6 when the app is built for it.
An activity is a screen
An Android app is made of activities, one per screen. In Ruboto an activity is a Ruby class with a method onCreate: Android calls it when the screen starts. It calls super first – Android insists –, then builds what the screen shows. Run the cell, and the app starts on the phone below it:
require 'ruboto/widget'
ruboto_import_widgets :TextView
class HelloActivity
def onCreate(bundle)
super
set_title 'Hello'
self.content_view = text_view text: 'Chunky bacon!', text_size: 32, gravity: :center
end
end
ruboto_import_widgets :TextView fetches the Java class android.widget.TextView and gives every activity a method named after it in snake case: text_view. Its options are calls to Java setters – text: calls setText, text_size: setTextSize –, and the symbol :center stands for the Java constant Gravity::CENTER. content_view= is Android's setContentView: this view fills the screen. Inside onCreate, self is the activity itself, the Java object Android made: Ruboto defines the class's methods on it.
Try the buttons below the screen: ● goes to the home screen, where the fox starts the app again; ◀ goes back – on an app's first screen that sends the app to the background too, since Android 12.
The app ruboto gen app writes
A new Ruboto app starts with the activity below – Ruboto's own sample, unchanged. A button takes a proc as its on_click_listener. Android wants a Java object with a method onClick, a View.OnClickListener, and JRuby makes one from the proc – as it made a Comparator from a block in lesson 94. toast is Ruboto's: it shows Android's short message at the bottom of the screen.
require 'ruboto/widget'
require 'ruboto/toast'
ruboto_import_widgets :Button, :LinearLayout, :TextView
# http://xkcd.com/378/
class SampleActivity
def onCreate(bundle)
super
set_title 'Domo arigato, Mr Ruboto!'
self.content_view =
linear_layout :orientation => :vertical do
@text_view = text_view :text => 'What hath Matz wrought?', :id => 42,
:layout => {:width => :match_parent},
:gravity => :center, :text_size => 48.0
button :text => 'M-x butterfly',
:layout => {:width => :match_parent},
:id => 43, :on_click_listener => proc { butterfly }
end
rescue Exception
puts "Exception creating activity: #{$!}"
puts $!.backtrace.join("\n")
end
private
def butterfly
@text_view.text = 'What hath Matz wrought!'
toast 'Flipped a bit via butterfly'
end
end
Tap M-x butterfly (the joke is from xkcd 378, about real programmers). The text changes and a toast comes up. Now rotate the phone with ⟳ above it: the question mark is back. That is not the simulation's fault. When a phone turns, Android ends the activity and starts a new one, which runs onCreate again – and what the old one held is gone.
The life of an activity
Android calls more than onCreate, always in the same order: onStart and onResume when the screen shows, onPause and onStop when it goes away (Home, another app), onDestroy at the end. Whenever Android stops an activity it may need again – Home, another screen on top, a rotation (which then ends it and makes a new one) – it calls onSaveInstanceState (since Android 9 right after onStop) with a Bundle, a small Java Hash for numbers and strings; a new activity made for it gets that Bundle in onCreate. Why not simply a global variable? Android may end the whole app process while it waits in the background; the Bundle is kept outside the process, a $variable is not. This activity writes each call to logcat, Android's log, which you see beside the phone. android.util.Log.d adds a line at level D (debug), with a tag to find it by:
require 'ruboto/widget'
ruboto_import_widgets :LinearLayout, :TextView, :Button
class LifeActivity
def onCreate(bundle)
super
log "onCreate, bundle: #{bundle || 'nil'}"
@taps = bundle ? bundle.getInt('taps') : 0
set_title 'The life of an activity'
self.content_view = linear_layout orientation: :vertical, padding: [16, 16, 16, 16] do
@label = text_view text: "#{@taps} taps", text_size: 28
button text: 'Tap', on_click_listener: proc { add_tap }
end
end
def onStart; super; log 'onStart'; end
def onResume; super; log 'onResume'; end
def onPause; super; log 'onPause'; end
def onStop; super; log 'onStop'; end
def onDestroy; super; log 'onDestroy'; end
def onSaveInstanceState(out_state)
super
out_state.putInt('taps', @taps)
log "onSaveInstanceState: #{@taps} taps"
end
def add_tap
@taps += 1
@label.text = "#{@taps} taps"
end
def log(text)
android.util.Log.d('Life', text)
end
end
Tap a few times, then rotate. Logcat shows the whole dance: onPause, onStop, onSaveInstanceState, onDestroy – and a new onCreate whose bundle holds your taps, so they stay. Press ● (Home): onPause, onStop and onSaveInstanceState, the activity waits; the fox brings it back with onStart and onResume. ◀ on an app's first screen does the same since Android 12 – the app goes to the background. An activity that ◀ really ends, with onDestroy and no bundle, comes below: the photo frame's second screen. (What puts prints inside the app also lands in logcat, under the tag System.out, as on a phone.)
A list, a menu, a dialog
A shopping list: an EditText to type into, a ListView for the items. list: hands the list an Array; after a change, Ruboto's reload_list shows it anew. The menu behind ⋮ comes from onCreateOptionsMenu, and a tap on an item asks with an AlertDialog. Its Builder is a Java class whose setters each return the builder, so the calls chain – in snake case, as JRuby allows:
require 'ruboto/widget'
require 'ruboto/toast'
ruboto_import_widgets :LinearLayout, :EditText, :Button, :ListView
class ShoppingActivity
def onCreate(bundle)
super
set_title 'Shopping list'
@items = ['Coffee', 'bacon', 'Eggs']
self.content_view = linear_layout orientation: :vertical, padding: [16, 8, 16, 8] do
linear_layout do
@field = edit_text hint: 'What else?', layout: { width: 0, weight: 1 }
button text: 'Add', on_click_listener: proc { add_item }
end
@list = list_view list: @items, on_item_click_listener: proc { |list, view, position, id|
ask_remove(position)
}
end
end
def onCreateOptionsMenu(menu)
menu.add('Sort').set_on_menu_item_click_listener { sort_items; true }
menu.add('Empty the list').set_on_menu_item_click_listener { @items.clear; refresh; true }
true
end
def add_item
text = @field.text.to_s.strip
return toast('Type something first') if text.empty?
@items << text
refresh
@field.text = ''
end
def sort_items
@items.sort_by!(&:downcase)
refresh
end
def refresh
@list.reload_list(@items)
end
def ask_remove(position)
android.app.AlertDialog::Builder.new(self)
.set_title(@items[position])
.set_message('Got it? Then it comes off the list.')
.set_positive_button('Remove', proc { |_, _| @items.delete_at(position); refresh })
.set_negative_button('Keep', nil)
.show
end
end
Two things to see here. set_on_menu_item_click_listener { … } takes a block instead of a proc: JRuby turns either into the Java interface. And the block answers true – Java's onMenuItemClick returns a boolean that says “handled” (onCreateOptionsMenu must answer true too: false means no menu, and a forgotten answer – the last line's value, nil or a MenuItem – crashes the app on a phone, as it does here). Sort uses sort_by!(&:downcase): a plain sort puts all capitals first, so the lowercase “bacon” would land after “Eggs”.
A photo frame
Ruboto's README mentions it: a cheap digital photo frame often runs an old Android, and Ruboto apps can be built for those down to Android 6. Here is the app for one. Its pictures are NASA photos (public domain), in the app's res/drawable folder; Android's build gives each a number in the class R, so R.drawable.earthrise is the Earth rising over the Moon. An ImageView shows one; a Handler runs the next step after 4 seconds; a tap on the photo opens a second screen with start_ruboto_activity, and ◀ comes back:
require 'ruboto/widget'
ruboto_import_widgets :LinearLayout, :ImageView, :TextView, :Button
class PhotoFrameActivity
PHOTOS = {
R.drawable.earthrise => 'Earthrise – Apollo 8, 24 December 1968',
R.drawable.blue_marble => 'The Blue Marble – Apollo 17, 1972',
R.drawable.moonwalk => 'Buzz Aldrin on the Moon – Apollo 11, 1969',
R.drawable.saturn_v => 'A Saturn V lifts off – Apollo 11, 1969',
R.drawable.aurora => 'Aurora below the space station – 2019',
R.drawable.hurricane => 'Hurricane Milton from the space station – 2024'
}
SECONDS = 4
def onCreate(bundle)
super
set_title 'Photo frame'
@index = bundle ? bundle.getInt('index') : 0
@handler = android.os.Handler.new(android.os.Looper.main_looper)
@tick = proc { step(1) }.to_java(java.lang.Runnable)
self.content_view = linear_layout orientation: :vertical, background_color: 0xFF000000 do
@photo = image_view scale_type: android.widget.ImageView::ScaleType::CENTER_CROP,
layout: { width: :match_parent, height: 0, weight: 1 },
on_click_listener: proc { show_details }
@caption = text_view text_color: 0xFFFFFFFF, gravity: :center, padding: [8, 8, 8, 8]
linear_layout gravity: :center do
button text: 'Back', on_click_listener: proc { step(-1) }
button text: 'Next', on_click_listener: proc { step(1) }
end
end
show(@index)
end
def onResume
super
@handler.postDelayed(@tick, SECONDS * 1000)
end
def onPause
super
@handler.removeCallbacks(@tick)
end
def onSaveInstanceState(out_state)
super
out_state.putInt('index', @index)
end
def step(by)
android.util.Log.d('Frame', "step in activity #{object_id}")
show(@index + by)
@handler.removeCallbacks(@tick)
@handler.postDelayed(@tick, SECONDS * 1000)
end
def show(index)
@index = index % PHOTOS.size
@photo.image_resource = PHOTOS.keys[@index]
@caption.text = PHOTOS.values[@index]
end
def show_details
start_ruboto_activity 'PhotoDetailsActivity', extras: { 'index' => @index } do
def onCreate(bundle)
super
index = getIntent.getLongExtra('index', 0)
set_title "Photo #{index + 1} of #{PhotoFrameActivity::PHOTOS.size}"
self.content_view = linear_layout orientation: :vertical, padding: [16, 16, 16, 16] do
image_view image_resource: PhotoFrameActivity::PHOTOS.keys[index],
layout: { width: :match_parent, height: 0, weight: 1 }
text_view text: PhotoFrameActivity::PHOTOS.values[index], text_size: 18, gravity: :center
text_view text: 'Photo: NASA (public domain)', gravity: :center
end
android.util.Log.d('Frame', 'details: onCreate')
end
def onDestroy
super
android.util.Log.d('Frame', 'details: onDestroy')
end
end
end
end
The Handler is Android's timer for the screen: made with Looper.main_looper, it runs a Runnable with postDelayed later on the main thread, the one that draws, and step posts the next one. Two details matter on a real phone:
removeCallbacksinonPause. A posted Runnable outlives its activity. Without it, every rotation leaves the old, invisible activity ticking – for ever, and holding on to its views and photos. (DeleteonPause, run the cell, rotate twice and watch logcat:stepnow runs in three activities, two of them on screens nobody sees.).to_java(java.lang.Runnable). On a phone, JRuby makes a new Java object each time a proc is handed to Java, andremoveCallbackswith a new object finds nothing. Converted once and kept in@tick, it is the same object every time. (This browser JRuby happens to keep the conversion; Ruboto's README warns about the phone.)
The details screen is a class made from the block of start_ruboto_activity. It gets the photo's number as an extra of the Intent – Android's message to start an activity – and reads it with getIntent.getLongExtra: a Ruby Integer goes to Java as a long, and getIntExtra would find nothing (logcat says so, with Android's own warning). ◀ on this screen ends it for good – logcat shows its onDestroy – and the photo frame comes back.
On a real phone the same Ruby goes into an APK. With Ruboto 2 (github.com/Largo/ruboto), a JDK 17 or newer, Gradle and the Android SDK (ANDROID_HOME pointing to it) – Android Studio is not needed; --min-sdk 23 builds it for Android 6, as on an old photo frame:
git clone https://github.com/Largo/ruboto.git
cd ruboto && bundle install && cd ..
ruby -Iruboto/lib ruboto/bin/ruboto gen app --package org.ruboto.example --name PhotoFrame --path photo_frame --min-sdk 23
cd photo_frame && gradle assembleDebug
adb install app/build/outputs/apk/debug/app-debug.apkThe activity goes into app/src/main/resources/photo_frame_activity.rb – Ruboto finds the class by the file's name, so PhotoFrameActivity needs exactly that one –, the photos into app/src/main/res/drawable/. A debug build of a small Ruboto app here was 24 MB – most of it JRuby. On the phone, JRuby is interpreted, and starting it takes seconds; Ruboto shows a splash screen meanwhile. What this simulation leaves out: layouts in XML, Java classes that Ruby subclasses (Android cannot load classes made at run time, so Ruboto cannot do that either), the camera, sensors, the network, threads – and any Android class not in the list of stand-ins.
Look it up: Ruboto 2's README (Java callbacks, gems, older phones), the sample activities, and Android's guide to the activity lifecycle.
CounterActivity counts the taps on +1 – but rotate the phone, and it starts at 0 again. Give it an onSaveInstanceState(out_state) that puts the count into the bundle (super first), and let onCreate take it from there when there is a bundle. The check taps +1 three times, rotates, and taps once more: then the counter must say 4.require 'ruboto/widget'
ruboto_import_widgets :LinearLayout, :TextView, :Button
class CounterActivity
def onCreate(bundle)
super
set_title 'Counter'
@count = 0
self.content_view = linear_layout orientation: :vertical, gravity: :center do
@label = text_view text: @count.to_s, text_size: 64, gravity: :center
button text: '+1', on_click_listener: proc { count_up }
end
end
def count_up
@count += 1
@label.text = @count.to_s
end
end