Accessing network from Ruboto

165 Views Asked by At

I'm trying to use Ruby-DRb-Messages from Android with Ruboto. I ran into a problem acessing network from Ruboto and did not find any example or documentation to solve this issue.

This is my example (I used Ruboto QuickStartActivity and tried to add my stuff):

require 'ruboto/widget'
require 'ruboto/util/toast'
require 'drb'

ruboto_import_widgets :Button, :LinearLayout, :TextView

class QuickStartActivity
  def onCreate(bundle)
    super
    set_title 'My Title'
    self.content_view =
        linear_layout :orientation => :vertical do
          @text_view = text_view :text => 'Test Buttons', :id => 42, 
                                 :layout => {:width => :match_parent},
                                 :gravity => :center, :text_size => 48.0
          button :text => 'Press me', 
                 :layout => {:width => 300},
                 :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 = 'Button pressed'
    toast "trying to send a message"
    DRb.start_service
    myDRb = DRbObject.new_with_uri("druby://192.168.1.100:9918")
    myDRb.myMethod('This string should be processed by myMethod')
  end
end

If I use two Linux-machines (DRb-Server and DRb-Client), DRb-stuff works without problems through network. But if I try my code above, logcat shows:

D/AndroidRuntime(17415): Shutting down VM
W/dalvikvm(17415): threadid=1: thread exiting with uncaught exception (group=0x2b4ea1f8)
E/AndroidRuntime(17415): FATAL EXCEPTION: main
E/AndroidRuntime(17415): android.os.NetworkOnMainThreadException
E/AndroidRuntime(17415):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
E/AndroidRuntime(17415):    at java.net.InetAddress.lookupHostByName(InetAddress.java:391)

My Android-Manifest includes:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

According to other posts (How to fix android.os.NetworkOnMainThreadException?) I read, this error is thrown because it is not possible to use network from main thread in Android.

But how can I fix this issue on Ruboto-side to get DRb working?

1

There are 1 best solutions below

1
On

One way to do this is to execute your network code in a Thread, and then use a callback for the result.

def butterfly
  @text_view.text = 'Button pressed'
  toast "trying to send a message"
  Thread.start do
    DRb.start_service
    myDRb = DRbObject.new_with_uri("druby://192.168.1.100:9918")
    result = myDRb.myMethod('This string should be processed by myMethod')
    process_result(result)
  end
end

def process_result(result)
  run_on_ui_thread do
    @text_view.text = 'Result received'
    toast "Got a result from the method: #{result}"
  end
end

Hope this helps :)