将字符串发送到Java Application时Android应用程序中的问题

时间:2015-08-11 18:06:37

标签: java android string sockets networking

尝试创建一个简单的应用程序,从语音API接收文本并将其发送到java服务器。从跟踪调试。代码不会超出我打开插座的TRY块。

代码更新:现在应用程序没有崩溃。但没有消息流。

package info.androidhive.speechtotext;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Locale;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import static java.sql.DriverManager.println;


public class MainActivity extends Activity {

    /**
     * Declarations
     */
    private TextView txtSpeechInput;

    private ImageButton btnSpeak;

    String str;

    private final int REQ_CODE_SPEECH_INPUT = 100;

    private String serverIpAddress = "";

    private boolean connected = false;

    TextView textIn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
        btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

        // hide the action bar
        getActionBar().hide();

        btnSpeak.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                promptSpeechInput();
            }
        });

    }

    /**
     * Showing google speech input dialog
     */
    private void promptSpeechInput() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                getString(R.string.speech_prompt));
        try {
            startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
        } catch (ActivityNotFoundException a) {
            Toast.makeText(getApplicationContext(),
                    getString(R.string.speech_not_supported),
                    Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * Receiving speech input
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_CODE_SPEECH_INPUT: {
                if (resultCode == RESULT_OK && null != data) {

                    ArrayList<String> result = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    txtSpeechInput.setText(result.get(0));
                    str = result.get(0);
                    setContentView(R.layout.activity_main);
                    Log.d("1- naval", " client oncreate");

                    Button button = (Button) findViewById(R.id.send);
                    textIn = (TextView) findViewById(R.id.textin);
                    /**
                     * Setting the text box with default value
                     */
                    textIn.setText(str);
                    Log.d("settext", " 2-naval");
                    /**
                     * Here we need to fill in textin from MainActivity,
                     * where we received the speech API text
                     */
                    button.setOnClickListener(new View.OnClickListener() {

                                                  @Override
                                                  public void onClick(View arg0) {
                                                      if (!connected) {
                                                          serverIpAddress = "192.168.0.4";
                                                          if (!serverIpAddress.equals("")) {
                                                              Thread cThread = new Thread(new ClientThread());
                                                              cThread.start();
                                                          }
                                                      }
                                                  }
                                              }
                    );


                }
            }
        }
    }

    public class ClientThread implements Runnable {

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                Log.d("ClientActivity", "C: Connecting...");
                Socket socket = new Socket(serverAddr, 8888);
                PrintWriter out = null;
                out.println(str);
                connected = true;
                while (connected) {
                    try {
                        Log.d("ClientActivity", "C: Sending command.");
                        out = new PrintWriter(
                                new BufferedWriter(new OutputStreamWriter(
                                        socket.getOutputStream())), true);
                        // WHERE YOU ISSUE THE COMMANDS
                        // out.println("Hey Server!");
                        Log.d("ClientActivity", "C: Sent.");
                    } catch (Exception e) {
                        Log.e("ClientActivity", "S: Error", e);
                    }
                }
                socket.close();
                Log.d("ClientActivity", "C: Closed.");
            } catch (Exception e) {
                Log.e("ClientActivity", "C: Error", e);
                connected = false;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

因为在写这个答案的时候,作者还没有添加一个堆栈跟踪,我将讨论一些基本的解决方案:

  • 确保您已为Android清单添加了INTERNET权限,否则您的套接字将无法打开<uses-permission android:name="android.permission.INTERNET" />
  • 在后台线程上打开您的套接字。在Android
  • 上禁止在UI线程上联网(例如在onClick方法内部)
  • 如果以上方法无法解决您的问题,请添加堆栈跟踪