Skip to content

Using Services and BroadcastReceivers

Scott Moyer edited this page Apr 6, 2014 · 1 revision

Creating a BroadcastReceiver at Runtime

Create your app:

ruboto gen app --package org.ruboto.example.broadcast_receiver_example
cd broadcast_receiver_example

Edit the file src/broadcast_receiver_example_activity.rb to match the code:

require 'ruboto/activity'
require 'ruboto/widget'

ruboto_import_widgets :TextView

class MyReceiver < android.content.BroadcastReceiver
  def initialize(activity)
    super()
    @activity = activity
  end
  
  def onReceive(context, intent)
    @activity.puts intent.action
  end
end

class BroadcastReceiverExampleActivity
  def puts(str)
    @tv.append str 
    @tv.append "\n" 
  end
  
  def on_create(b)
    super
    self.content_view = (@tv = text_view(:text => "Waiting for Broadcast actions:\n"))

    @br = MyReceiver.new(self)

    @if = android.content.IntentFilter.new
    @if.add_action android.content.Intent::ACTION_POWER_CONNECTED
    @if.add_action android.content.Intent::ACTION_POWER_DISCONNECTED
    @if.add_action android.content.Intent::ACTION_SCREEN_ON
    @if.add_action android.content.Intent::ACTION_SCREEN_OFF
    
    register_receiver @br, @if
  end
      
  def on_destroy
    super
    unregister_receiver(@br)
  end
end

When you turn your screen on/off or plug/unplug your device, you will see the intent name displayed in the TextView.

Clone this wiki locally