我的android应用程序有一个基于ASyncTask的客户端套接字似乎坏了

时间:2012-05-14 08:20:47

标签: android multithreading sockets networking android-asynctask

我正在尝试使用ASyncTask来处理我的Android应用程序后台的网络。 SendData中发生的任何事情都在一个单独的线程中。后台线程开始运行,打印前两条日志消息。然后它挂了。我对android和socket都很陌生,所以如果有很多错误我也不会感到惊讶。

package light24bulbs.ioio.testing;

import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.Button;
import android.widget.Toast;
import ioio.lib.api.PwmOutput;
import android.view.*;
import android.widget.TextView;
import android.util.Log;
import light24bulbs.ioio.testing.R;
import java.io.*;
import java.net.*;
import android.os.AsyncTask;
import android.view.View.*;

public class MainActivity extends IOIOActivity {
    private SeekBar bar_;
    private final int servoPin = 11;
    private final int freq = 100;
    private final String serverIP="192.168.1.41";
    TextView progressText;
    Button open;
    int progress;
    SendData senddata;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bar_ = (SeekBar) findViewById(R.id.seekBar1);
        TextView progressText = (TextView) findViewById(R.id.textView1);
        open = (Button) findViewById(R.id.start);
        open.setOnClickListener(openSocket);
        senddata = new SendData();
        senddata.execute(serverIP,null,null);


    }


    class Looper extends BaseIOIOLooper {
        /** The on-board LED. */
        private PwmOutput servo_;

        //happens when IOIO module is connected
        @Override
        protected void setup() throws ConnectionLostException {

            servo_ = ioio_.openPwmOutput(servoPin, freq);



        }

//loops forever once everything else has been set up
        @Override
        public void loop() throws ConnectionLostException {

            servo_.setPulseWidth(600+(bar_.getProgress()*20));
            //servo_.setPulseWidth(800);
             progress = bar_.getProgress();
             senddata.onProgressUpdate(progress);

             try{
                 Thread.sleep(20);
             }catch(InterruptedException e){

             }
        }
    }

    @Override
    protected IOIOLooper createIOIOLooper() {
        return new Looper();
    }


private class SendData extends AsyncTask<String, Integer, Boolean>{
    Socket clientSocket;
    DataOutputStream toServer;
    PrintStream pStream;
    @Override
    protected Boolean doInBackground(String... IP){
        Log.i("AsyncTask","doInBackground started running");
        Log.i("AsyncTask","attempting to connect to ip: "+IP[0]);
        try{


        clientSocket = new Socket(IP[0],4488);
        Log.i("AsyncTask","Created socket"+String.valueOf(clientSocket));
        toServer = new DataOutputStream(clientSocket.getOutputStream());
        }catch(IOException e){
            Log.i("AsyncTask","IO Exception while connecting socket- doInbackground()");
            return false;
        }
        Log.i("AsyncTask","Port connected! "+IP[0]);
        return true;
    }
    @Override
    protected void onProgressUpdate(Integer...pos){
        try{
        toServer.writeBytes(String.valueOf(pos[0]));
        }catch(IOException e){
            Log.i("AsyncTask","Failed to send the position");
        }
    }





}
}

1 个答案:

答案 0 :(得分:1)

对于初学者,protected void onProgressUpdate(Integer...pos)在UI线程上运行。

这通常是向网络发送内容的最佳位置 - 您的想法是使用此方法更新UI,例如更新包含计数器或进度对话框的TextView

其次,#doInBackground(..)的实现将设置套接字并立即退出,将Thread返回给线程池支持AsyncTask

如果要向服务器发送多个包,则必须在此处创建循环。此外 - 您对[{1}}的调用(并进行任何循环)也应在toServer中完成 - 如果您想更新自己的用户界面,请从调用doInBackground() #publishProgress(..) - 会将您要展示的数据传递给#doInBackground()