Android编程:通过AsyncTask处理TCP时有问题



我遇到的问题是,我的程序只能通过AsyncTask通过TCP发送我的字符串。我读到AsyncTask只能运行一次,在它运行后,它应该被处置,如果我需要发送另一个命令,我应该创建线程的另一个实例,并使用新实例发送新命令。然而,无论出于何种原因,当我试图创建我的AsyncTask的第二个实例时,什么都不会发生。值得注意的事情。我在onPostExecute例程中添加了一个日志命令,但是我从来没有看到日志消息。

我有以下在我的Android-Manifest文件:

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

这是主活动线程中调用异步任务的代码。

public void SendCommand(int DeviceID, String DeviceName, String CommandName)
{
    //Get the IP address and the port in order to communicate with the device
    DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this);
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    String dbQuery = "SELECT * FROM " + dbHelper.System_Table + ", " + dbHelper.Devices_Table + ", " +
            dbHelper.Device_Commands_Table + " WHERE " + dbHelper.System_Table + "." + dbHelper.Attribute_Device_ID +
            " = " + String.valueOf(DeviceID) + " AND " + dbHelper.Devices_Table + "." + dbHelper.Attribute_Device_ID +
            " = " + String.valueOf(DeviceID) + " AND " + dbHelper.Device_Commands_Table + "." + dbHelper.Attribute_Device_ID +
            " = " + String.valueOf(DeviceID) + ";";
    Cursor c = db.rawQuery(dbQuery, null);
    String IPAddress = "";
    int Port = 0;
    String DeviceCommand = "";
    if (c.getCount() > 0)
    {
        int Finished = 0;
        while (c.moveToNext() && Finished == 0)
        {
            int iColumnDeviceName = c.getColumnIndex(dbHelper.Attribute_Device_Name);
            int iColumnDeviceCommandName = c.getColumnIndex(dbHelper.Attribute_Command_Name);
            final String CheckDeviceName = c.getString(iColumnDeviceName);
            final String CheckCommandName = c.getString(iColumnDeviceCommandName);
            if (DeviceName.equals(CheckDeviceName) && CheckCommandName.equals(CommandName))
            {
                Finished = 1;
                int iColumnIPAddress = c.getColumnIndex(dbHelper.Attribute_Device_IP);
                int iColumnPort = c.getColumnIndex(dbHelper.Attribute_Device_Port);
                int iColumnDeviceCommandString = c.getColumnIndex(dbHelper.Attribute_Command_String);
                IPAddress = c.getString(iColumnIPAddress);
                Port = c.getInt(iColumnPort);
                DeviceCommand = c.getString(iColumnDeviceCommandString);
                DeviceCommand = DeviceCommand.replace("<CR>", "r");
                Log.d("Device Command To Send", DeviceCommand);
            }
        }
        c.close();
        dbHelper.close();
        ArrayList<String> passing = new ArrayList<String>();
        ArrayList<String> result = new ArrayList<String>();
        passing.add(IPAddress);
        passing.add(String.valueOf(Port));
        passing.add(DeviceCommand);
        SendCommand SC = new SendCommand();
        SC.execute(passing, result);
    }
}

这是上面例程创建并执行的单独的类文件。

public class SendCommand extends AsyncTask<ArrayList<String>, Void, ArrayList<String>>
{
    @Override
    protected void onPreExecute()
    {
        //progress bar
    }
    @Override
    protected ArrayList<String> doInBackground(ArrayList<String>... passing)
    {
        Log.d("Async Task", "Started to send command.");
        //Get the connection info and command to send from the caller
        String Data = passing[0].toString();
        int StopAt = Data.indexOf(",");
        String IPAddress = Data.toString().substring(1, StopAt);
        Data = Data.replace("[" + IPAddress + ", ", "");
        StopAt = Data.indexOf(",");
        int Port = Integer.parseInt(Data.toString().substring(0, StopAt));
        Data = Data.replace(Port + ", ", "");
        StopAt = Data.indexOf("]");
        String DeviceCommand = Data.toString().substring(0, StopAt);
        Send_Command(IPAddress, Port, DeviceCommand);
        return null;
    }
    protected void onPostExecute(Long result)
    {
        Log.d("Async Task", "Command Sent");
    }
    private void Send_Command(String IPAddress, int Port, String DeviceCommand)
    {
        //Setup the connection parameters
        SocketAddress SA = new InetSocketAddress(IPAddress, Port);
        int Timeout = 2000;
        Socket socket = new Socket();
        try
        {
            //Attempt to connect to the device
            socket.connect(SA, Timeout);
            int Count = 0;
            int Kill = 0;
            while (socket.isConnected() == false && Kill == 1)
            {
                //Waiting for the connection
                Count = Count + 1;
                if (Count == Timeout)
                {
                    Kill = 1;
                    Log.d("Connection Status", "Timed out");
                }
            }
            if (socket.isConnected() == true)
            {
                //send the command
                BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                wr.write(DeviceCommand);
                wr.flush();
                Log.d("Sent Device Command", DeviceCommand);
                //listen for the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String Response;
                while ((Response = rd.readLine()) != null)
                {
                    Log.d("Received Device Response", Response);
                }
                rd.close();
            }
            //close the socket once the response is received
            socket.close();
        }
        catch (UnknownHostException e)
        {
            Log.d("UnknownHostException", "Something bad happened");
        }
        catch (IOException e)
        {
            Log.d("IOException", "Something bad happened");
        }
        finally
        {
            if (socket != null)
            {
                try
                {
                    socket.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}

最后这是我尝试通过tcp发送两个命令后的日志。

01-14 23:53:29.773: D/Device Command To Send(31643): PN
01-14 23:53:29.773: D/Async Task(31643): Started to send command.
01-14 23:53:30.108: D/Sent Device Command(31643): PN
01-14 23:53:30.273: D/Received Device Response(31643): R
01-14 23:53:31.918: D/Device Command To Send(31643): PF

我可以看到AsyncTask第一次启动,它发送命令以及从目标设备接收响应。然而,我没有看到"异步任务","命令发送"在日志中,所以onPostExecute没有执行。

有什么想法我做错了吗?

您的onPostExecute签名错误。

protected void onPostExecute(Long result)

应该是

protected void onPostExecute(ArrayList<String> result)

也可以使用@Override注释。

把一些额外的调试信息在你的Send_Command, AsyncTask可能挂在那里。

目前您没有从AsyncTask重写onPostExecute,所以更改您的onPostExecute签名为:

@Override
protected void onPostExecute(ArrayList<String> result)//<Change Long
                                                      // to ArrayList<String>
  {
       Log.d("Async Task", "Command Sent");
  }

相关内容

  • 没有找到相关文章

最新更新