从Ruboto访问网络

时间:2015-01-31 10:52:40

标签: ruby ruboto drb

我正在尝试使用来自Android的Ruby-DRb-Messages和Ruboto。我遇到了一个从Ruboto进入网络的问题,并没有找到任何解决此问题的示例或文档。

这是我的例子(我使用Ruboto QuickStartActivity并试图添加我的东西):

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

如果我使用两台Linux机器(DRb-Server和DRb-Client),DRb-stuff可以通过网络正常运行。但如果我尝试上面的代码,logcat会显示:

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)

我的Android-Manifest包括:

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

根据我读过的其他帖子(How to fix android.os.NetworkOnMainThreadException?),这个错误  抛出是因为在Android中无法使用主线程中的网络。

但是我怎么能在Ruboto端修复这个问题才能让DRb工作?

1 个答案:

答案 0 :(得分:0)

一种方法是在线程中执行网络代码,然后对结果使用回调。

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

希望这会有所帮助:)