2014-03-28 72 views
0

我想使用Android的服務發送數據到Unity,我一直在跟隨這tutorial這樣做,並完美的工作,但我需要創建一個套接字連接接收數據一個服務器,然後將其作爲廣播消息發送,就像教程所示。問題是,由於套接字連接啓動應用程序時,我得到NetworkOnMainThreadException。我已經看到使用AsyncTask可能可以解決問題,但我仍然不知道如何實現該服務並以此方式發送廣播消息。Android的Unity服務NetworkOnMainThreadException

這是服務代碼:

private final Handler handler = new Handler(); 


// It's the code we want our Handler to execute to send data 
private Runnable sendData = new Runnable() { 
     // the specific method which will be executed by the handler 
     public void run() { 

       Socket socket = null; 

       try{ 

        socket = new Socket("x.x.x.x", 1337); 

        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

        String line =""; 

        line = input.readLine();      

        numIntent++; 

        // sendIntent is the object that will be broadcast outside our app 
        Intent sendIntent = new Intent(); 

        // We add flags for example to work from background      
        sendIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_FROM_BACKGROUND|Intent.FLAG_INCLUDE_STOPPED_PACKAGES ); 

        // SetAction uses a string which is an important name as it identifies the sender of the itent and that we will give to the receiver to know what to listen. 
        // By convention, it's suggested to use the current package name 
        sendIntent.setAction("com.test.service.IntentToUnity"); 

        // Here we fill the Intent with our data, here just a string with an incremented number in it. 
        //sendIntent.putExtra(Intent.EXTRA_TEXT, "Intent "+numIntent); 
        sendIntent.putExtra(Intent.EXTRA_TEXT, line); 
        // And here it goes ! our message is send to any other app that want to listen to it. 
        sendBroadcast(sendIntent); 

        // In our case we run this method each second with postDelayed 
        handler.removeCallbacks(this); 
        handler.postDelayed(this, 1000); 

       }catch(IOException e){ 
        e.printStackTrace(); 

       } 
     } 
}; 

// When service is started 
@Override 
public void onStart(Intent intent, int startid) { 
     // We first start the Handler 
     handler.removeCallbacks(sendData); 
     handler.postDelayed(sendData, 1000); 
} 

我不知道這是否因爲這些簡單的問題是我與Android服務和統一的第一步,但我還沒有找到一個解決的辦法。 任何建議是很好的讚賞,或者如果你知道另一種方式發送數據統一從一個android服務的套接字連接將是偉大的! 感謝您的幫助!

回答

0

Service切換到IntentService,應該解決問題。 IntentService在單獨的線程上運行,而Service在UI上運行線程

+0

感謝您的回答。我仍然有與IntentService更改相同的錯誤:'E/AndroidRuntime(15694):android.os.NetworkOnMainThreadException'。要調用服務,我只在'onCreate'函數上執行'this.startService(new Intent(this,LeapService.class));'。任何想法爲什麼? – user3472677

+0

刪除處理程序並再次嘗試 – Blackbelt

+0

但我該如何執行Runnable對象? – user3472677

相關問題