簡體   English   中英

在Android設備上打開套接字

[英]Socket Opening on Android Device

我知道這似乎是一個重復的問題,但實際上並非如此。 我想通過套接字與一些傳感器通信。 該連接在Emulator上工作正常,但是當我在Android設備上將其上傳時,它將無法正常工作。 調試后,我將應用程序縮小為使用以下代碼簡單地打開套接字。

try
{
 Socket socket = new Socket(InetAddress.getByName(ipAddress).getHostAddress(), 10001);
}
catch (Exception e)
{
 Toast.makeText(context, "Error: "+e.getMessage(), duration).show();
}

我只是打開一個套接字。這在仿真器上可以正常工作,但是當我在設備上運行該應用程序時,它掛了一段時間,甚至沒有顯示異常消息,卻什么也沒告訴我...任何想法可能是問題所在。 (最初是StrictMode問題,但我進行了梳理)。 LogCat上沒有錯誤。 我已經安裝了android終端模擬器並嘗試ping操作,回復很好。 提前致謝


這是代碼

import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class MainActivity extends Activity implements OnClickListener {
    Button btn;
    private CharSequence text = "";
    private Socket s;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork()   // or .detectAll() for all detectable problems
        .penaltyLog()
        .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects()
        .detectLeakedClosableObjects()
        .penaltyLog()
        .penaltyDeath()
        .build());

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(this);
    }

    public void onClick(View view){
        //detect the view that was "clicked"
        switch(view.getId())
        {
          case R.id.button1:
              new LongOperation().execute("");
          break;

        }

    }

    private class LongOperation extends AsyncTask<String, Void, String> {

          @Override
          protected String doInBackground(String... params) {

              try {
                    s = new Socket(InetAddress.getByName("o2215.airq.org").getHostAddress(), 10001);
                    text = "Connection Made";
                } catch (Exception e) {
                    text = "Error : ";
                    for(int i=0;i<e.getStackTrace().length;i++)
                    {
                        text = text +"\n"+ e.getStackTrace()[i];
                    }
                    e.printStackTrace();
                }
                return "";
          }      

          @Override
          protected void onPostExecute(String result) {
                TextView txt = (TextView) findViewById(R.id.output);
                txt.setText(text);
          }
    }
}

這在模擬器上可以正常工作,但在設備上不能正常工作。

也許是因為您嘗試在主UI線程中建立連接。 看起來您將上述代碼段放在了Activity類中。

您應該創建一個單獨的線程來與網絡進行通信。

使用簡單Thread或Android出色的AsyncTask

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM