views:

446

answers:

2

Hello, I am trying to send a file from the phone running Android 1.5 to a server on a desktop. I wrote some code, which works on emulator, but on the phone it doesn't. I'm connecting to the network through WiFi. It works, I can access the internet through my phone and I've configured my router. The application stops when I'm trying to connect. I have the permissions. Someone have any ideas, below is my code.

Running on Android

package br.ufs.reconhecimento;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;

/**
 * Sample code that invokes the speech recognition intent API.
 */
public class Reconhecimento extends Activity implements OnClickListener {

    static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
    static final String LOG_VOZ = "UFS-Reconhecimento";
    final int INICIAR_GRAVACAO = 01;
    int porta = 5158; // Porta definida no servidor
    int tempoEspera = 1000;
    String ipConexao = "172.20.0.189";
    EditText ipEdit;

    /**
     * Called with the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Inflate our UI from its XML layout description.
        setContentView(R.layout.main);

        // Get display items for later interaction
        ImageButton speakButton = (ImageButton) findViewById(R.id.btn_speak);
        speakButton.setPadding(10, 10, 10, 10);

        speakButton.setOnClickListener(this);

        //Alerta para o endereço IP
        AlertDialog.Builder alerta = new AlertDialog.Builder(this);
        alerta.setTitle("IP");//+mainWifi.getWifiState());

        ipEdit =  new EditText(this);
        ipEdit.setText(ipConexao);
        alerta.setView(ipEdit);
        alerta.setMessage("Por favor, Confirme o endereço IP.");
        alerta.setPositiveButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
                    ipConexao = ipEdit.getText().toString();
                    Log.d(LOG_VOZ, "Nova Atribuição do Endreço IP: " + ipConexao); } });
        alerta.create();
        alerta.show();

    }


    /**
     * Handle the click on the start recognition button.
     */
    public void onClick(View v) {
        if (v.getId() == R.id.btn_speak) {
            //startVoiceRecognitionActivity();
          Log.d(LOG_VOZ, "Iniciando a próxima tela");
          Intent recordIntent = new Intent(this, GravacaoAtivity.class);
          Log.d(LOG_VOZ, "Iniciando a tela (instancia criada)");
          startActivityForResult(recordIntent, INICIAR_GRAVACAO);
          Log.d(LOG_VOZ, "Gravação iniciada ...");
        }
    }


    /**
     * Handle the results from the recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     Log.d(LOG_VOZ, "Iniciando onActivityResult()");
     if (requestCode == INICIAR_GRAVACAO && resultCode == RESULT_OK) {
          String path = data.getStringExtra(GravacaoAtivity.RETORNO);
          conexaoSocket(path);
     }
     else
          Log.e(LOG_VOZ, "Resultado Inexperado ...");
    }

    private void conexaoSocket(String path) {
     Socket socket = SocketOpener.openSocket(ipConexao, porta, tempoEspera);
     if(socket == null)
          return;
     try {
               DataOutputStream conexao = new DataOutputStream(socket.getOutputStream());
               Log.d(LOG_VOZ, "Acessando arquivo ...");
               File file = new File(path);
               DataInputStream arquivo = new DataInputStream(new FileInputStream(file));
               Log.d(LOG_VOZ, "Iniciando Transmissão ...");
               conexao.writeLong(file.length());
               for(int i = 0; i < file.length(); i++)
                    conexao.writeByte(arquivo.readByte());
               Log.d(LOG_VOZ, "Transmissão realizada com sucesso...");
               Log.d(LOG_VOZ, "Fechando a conexão...");
               conexao.close();
               socket.close();
               Log.d(LOG_VOZ, "============ Processo finalizado com Sucesso ==============");
          } catch (IOException e) {
               Log.e(LOG_VOZ, "Erro ao fazer a conexão via Socket. " + e.getMessage());
               // TODO Auto-generated catch block
          }
    }

}

    class SocketOpener implements Runnable {

     private String host;
     private int porta;
     private Socket socket;

     public SocketOpener(String host, int porta) {
          this.host = host;
          this.porta = porta;
          socket = null;
     }

     public static Socket openSocket(String host, int porta, int timeOut) {

          SocketOpener opener = new SocketOpener(host, porta);
          Thread t = new Thread(opener);
          t.start();
          try {
               t.join(timeOut);
          } catch(InterruptedException e) {
               Log.e(Reconhecimento.LOG_VOZ, "Erro ao fazer o join da thread do socket. " + e.getMessage());
               //TODO: Mensagem informativa
               return null;
          }
          return opener.getSocket();
     }

     public void run() {
          try {
               socket = new Socket(host, porta);

          }catch(IOException e) {
               Log.e(Reconhecimento.LOG_VOZ, "Erro na criação do socket. " + e.getMessage());
               //TODO: Mensagem informativa
          }
     }

     public Socket getSocket() {
          return socket;
     }

    }

Running on the desktop

Java:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class ServidorArquivo {

     private static int porta = 5158;

     static String ARQUIVO = "voz.amr";
     /**
      * Caminho que será gravado o arquivo de audio
      */
     static String PATH = "/home/iade/Trabalho/lib/";

     public static void main(String[] args) {

          int i = 1;
          try {
               System.out.println("Iniciando o Servidor Socket - Android.");
               ServerSocket s = new ServerSocket(porta);
               System.out.println("Servidor Iniciado com Sucesso...");
               System.out.println("Aguardando conexões na porta: " + porta);
               while(true) {
                    Socket recebendo = s.accept();
                    System.out.println("Aceitando conexão de nº " + i);
                    new ThreadedHandler(recebendo).start();
                    i++;
               }
               } catch (Exception e) {
                    System.out.println("Erro: " + e.getMessage());
                    e.printStackTrace();
               }
     }

}

class ThreadedHandler extends Thread {

     private Socket socket;

     public ThreadedHandler(Socket so) {
          socket = so;
     }

     public void run() {

          DataInputStream entrada = null;
          DataOutputStream arquivo = null;
          try {

               entrada = new DataInputStream(socket.getInputStream());
               System.out.println("========== Iniciando a leitura dos dados via Sockets ==========");
               long tamanho = entrada.readLong();
               System.out.println("Tamanho do vetor " + tamanho);
               File file = new File(ServidorArquivo.PATH + ServidorArquivo.ARQUIVO);
               if(!file.exists())
                    file.createNewFile();

               arquivo = new DataOutputStream(new FileOutputStream(file));
               for(int j = 0; j < tamanho; j++) {
                    arquivo.write(entrada.readByte());
               }
               System.out.println("========== Dados recebidos com sucesso ==========");

          } catch (Exception e) {
               System.out.println("Erro ao tratar do socket: " + e.getMessage());
               e.printStackTrace();
          } finally {
               System.out.println("**** Fechando as conexões ****");
               try {
                    entrada.close();
                    socket.close();
                    arquivo.close();
               } catch (IOException e) {
                    System.out.println("Erro ao fechar conex&#65533;es " + e.getMessage());
                    e.printStackTrace();
               }

          }
          System.out.println("============= Fim da Gravação ===========");

          // tratar o arquivo

          String cmd1 = "ffmpeg -i voz.amr -ab 12288 -ar 16000 voz.wav";
          String cmd2 = "soundstretch voz.wav voz2.wav -tempo=100";
          String dir = "/home/iade/Trabalho/lib";
          File workDir = new File(dir);
          File f1 = new File(dir+"/voz.wav");
          File f2 = new File(dir+"/voz2.wav");
          f1.delete();
          f2.delete();

          try {
               executeCommand(cmd1, workDir);
               System.out.println("realizou cmd1");
               executeCommand(cmd2, workDir);
               System.out.println("realizou cmd2");

          } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }

     }

     private void executeCommand(String cmd1, File workDir) throws IOException,
               InterruptedException {
          String s;
          Process p = Runtime.getRuntime().exec(cmd1,null,workDir);
          int i = p.waitFor();
          if (i == 0) {
               BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
               // read the output from the command
               while ((s = stdInput.readLine()) != null) {
                    System.out.println(s);
               }
          }
          else {
               BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
               // read the output from the command
               while ((s = stdErr.readLine()) != null) {
                    System.out.println(s);
               }
          }
     }

}

Thanks in advance.

+1  A: 

As you may know, you are giving an internal IP address for your workstation, 172.20.0.189. Whether your Android device can see that address when connected through the router could depend on your router settings, and how/if the workstation is connected to the same router.

It would be useful also if you would post your logcat output from around the time of the failure.

Jim Blackler
Oh, and more importantly the firewall on your workstation.
Jim Blackler
Hi,right now I'm trying to work on that, thanks for the advice.How do I get the logcat for my application? I'm not running it on emulator, but in the phone itself. Where does the OS saves the logs?Thanks
thiagolee
Open a console, 'cd' to the tools directory of your Android SDK, type 'adb -d logcat'. This will start showing you the logs of your phone. Run your app, get the error, and look at the most recent lines. You could also copy/paste them here.
Jim Blackler
I am almost sure that there's no problem with router configuration. I can run the program on an emulator on one PC and run the server on another and it works just fine. I configured the router and disabled the firewall for this. But the application on the phone just doesn't work.As for the logcat, I followed the instructions here http://wiki.openmoko.org/wiki/Android_on_Freerunner to connect the phone to the PC, but with no success. I can ping the device, but when I try to access it, it tells me "device not found", so I can't get the log for this reason. I'm running Ubuntu 9.10.
thiagolee
How are you loading the application if you don't have a working connection to the PC? APK via a memory card? Re. the data problem, is there some way you can expose the workstation server to the internet, that way you will rule out firewall problems etc.
Jim Blackler
I will try this option. I uploaded the APK file to an file upload service and downlaoded it to the phone and installed it.
thiagolee
A: 

Hi there, I managed to get my logcat for the application and it seems the problem lies in the recording process as ti seems, but I didn't manage to understand the whole log, here it is:

!!! HERE I START MY APPLCIATION!!!

I/ActivityManager(  868): Starting activity: Intent { action=android.intent.action.MAIN categories={android.intent.category.LAUNCHER} flags=0x10200000 comp={br.ufs.reconhecimento/br.ufs.reconhecimento.Reconhecimento} }                                                                                                                                              
W/UsageStats(  868): Something wrong here, Didn't expect com.android.launcher to be paused                                                                                          
I/ActivityManager(  868): Start proc br.ufs.reconhecimento for activity br.ufs.reconhecimento/.Reconhecimento: pid=1110 uid=10017 gids={3003}                                       
W/IInputConnectionWrapper(  937): showStatusIcon on inactive InputConnection                                                                                                        
I/ARMAssembler(  868): generated scanline__00000077:03515104_00000000_00000000 [ 45 ipp] (66 ins) at [0x254810:0x254918] in 0 ns                                                    
I/ActivityManager(  868): Displayed activity br.ufs.reconhecimento/.Reconhecimento: 4671 ms                                                                                         
D/dalvikvm( 1037): GC freed 1935 objects / 129832 bytes in 714ms                                                                                                                    
D/dalvikvm( 1059): GC freed 2338 objects / 163736 bytes in 359ms                                                                                                                    
D/dalvikvm(  937): GC freed 1818 objects / 120168 bytes in 883ms                                                                                                                    
D/UFS-Reconhecimento( 1110): Nova Atribuição do Endreço IP: 192.168.1.101                                                                                                           
D/dalvikvm( 1037): GC freed 1579 objects / 107712 bytes in 663ms                                                                                                                    
D/UFS-Reconhecimento( 1110): Iniciando a próxima tela                                                                                                                               
D/UFS-Reconhecimento( 1110): Iniciando a tela (instancia criada)

!!!HERE THE RECORDING (GRAVAÇÃO) STARTS!!!

I/ActivityManager(  868): Starting activity: Intent { comp={br.ufs.reconhecimento/br.ufs.reconhecimento.GravacaoAtivity} }                                                          
D/UFS-Reconhecimento( 1110): Gravação iniciada ...                                                                                                                                  
W/Resources( 1110): Converting to string: TypedValue{t=0x12/d=0x0 a=2 r=0x7f050000}                                                                                                 
E/ALSALib (  855): external/alsa-lib/src/pcm/pcm.c:2144:(snd_pcm_open_noupdate) Unknown PCM AndroidRecord_Speaker_normal                                                            
E/ALSALib (  855): external/alsa-lib/src/pcm/pcm.c:2144:(snd_pcm_open_noupdate) Unknown PCM AndroidRecord_Speaker                                                                   
E/ALSALib (  855): external/alsa-lib/src/pcm/pcm.c:2144:(snd_pcm_open_noupdate) Unknown PCM AndroidRecord                                                                           
I/AudioHardwareALSA(  855): Initialized ALSA CAPTURE device hw:00,0                                                                                                                 
D/AudioHardwareALSA(  855): Set CAPTURE PCM format to S16_LE (Signed 16 bit Little Endian)                                                                                          
E/AudioHardwareALSA(  855): Unable to set channel count to 1: Invalid argument                                                                                                      
W/AudioFlinger(  855): AudioRecordThread: buffer overflow                                                                                                                           
I/ActivityManager(  868): Displayed activity br.ufs.reconhecimento/.GravacaoAtivity: 634 ms                                                                                         
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000                                                                                    
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000                                                                                    
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000                                                                                    
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000                                                                                    
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000 

...
...  

!!!... IT STAYS ON IT FOR QUITE A BIT, EVEN AFTER I HIT THE ´STOP RECORDING AND SENDO AUDIO TO SERVER´ BUTTON...!!!

!!!THEN THE OS TELLS ME MY APPLICATION HAS CRASHED AND ASKS ME TO WAIT OR FORCE CLOSE!!!

W/WindowManager(  868): Key dispatching timed out sending to br.ufs.reconhecimento/br.ufs.reconhecimento.GravacaoAtivity                                                            
W/WindowManager(  868): Dispatch state: {{KeyEvent{action=1 code=4 repeat=0 meta=0 scancode=169 mFlags=8} to Window{474b590 com.android.launcher/com.android.launcher.Launcher paused=false} @ 946939940081 lw=Window{474b590 com.android.launcher/com.android.launcher.Launcher paused=false} lb=android.os.BinderProxy@474b3c8 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=Window{47a85c0 br.ufs.reconhecimento/br.ufs.reconhecimento.GravacaoAtivity paused=false}}}                                                                          
W/WindowManager(  868): Current state:  {{null to Window{47a85c0 br.ufs.reconhecimento/br.ufs.reconhecimento.GravacaoAtivity paused=false} @ 946940079807 lw=Window{47a85c0 br.ufs.reconhecimento/br.ufs.reconhecimento.GravacaoAtivity paused=false} lb=android.os.BinderProxy@47a83e0 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=Window{47a85c0 br.ufs.reconhecimento/br.ufs.reconhecimento.GravacaoAtivity paused=false}}}                                                                                                                   
I/ActivityManager(  868): ANR (application not responding) in process: br.ufs.reconhecimento                                                                                        
I/ActivityManager(  868): Annotation: keyDispatchingTimedOut                                                                                                                        
I/ActivityManager(  868): CPU usage:                                                                                                                                                
I/ActivityManager(  868): Load: 1.39 / 1.06 / 0.49                                                                                                                                  
I/ActivityManager(  868): CPU usage from 14065ms to 31ms ago:                                                                                                                       
I/ActivityManager(  868):   system_server: 0% = 0% user + 0% kernel                                                                                                                 
I/ActivityManager(  868):   com.android.phone: 0% = 0% user + 0% kernel                                                                                                             
I/ActivityManager(  868): TOTAL: 0% = 0% user + 0% kernel                                                                                                                           
I/ActivityManager(  868): Removing old ANR trace file from /data/anr/traces.txt                                                                                                     
I/Process (  868): Sending signal. PID: 1110 SIG: 3                                                                                                                                 
I/dalvikvm( 1110): threadid=7: reacting to signal 3                                                                                                                                 
I/Process (  868): Sending signal. PID: 937 SIG: 3                                                                                                                                  
I/dalvikvm(  937): threadid=7: reacting to signal 3                                                                                                                                 
I/Process (  868): Sending signal. PID: 1059 SIG: 3                                                                                                                                 
I/dalvikvm( 1059): threadid=7: reacting to signal 3                                                                                                                                 
I/Process (  868): Sending signal. PID: 972 SIG: 3                                                                                                                                  
I/dalvikvm(  972): threadid=7: reacting to signal 3                                                                                                                                 
I/Process (  868): Sending signal. PID: 1012 SIG: 3                                                                                                                                 
I/dalvikvm( 1012): threadid=7: reacting to signal 3                                                                                                                                 
I/Process (  868): Sending signal. PID: 1044 SIG: 3                                                                                                                                 
I/dalvikvm( 1044): threadid=7: reacting to signal 3                                                                                                                                 
I/Process (  868): Sending signal. PID: 1037 SIG: 3                                                                                                                                 
I/dalvikvm( 1037): threadid=7: reacting to signal 3                                                                                                                                 
I/Process (  868): Sending signal. PID: 1028 SIG: 3                                                                                                                                 
I/dalvikvm( 1028): threadid=7: reacting to signal 3                                                                                                                                 
I/Process (  868): Sending signal. PID: 1003 SIG: 3                                                                                                                                 
I/dalvikvm( 1003): threadid=7: reacting to signal 3                                                                                                                                 
I/Process (  868): Sending signal. PID: 868 SIG: 3                                                                                                                                  
I/dalvikvm(  868): threadid=7: reacting to signal 3                                                                                                                                 
I/dalvikvm( 1044): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
I/dalvikvm( 1028): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
I/dalvikvm( 1037): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
I/dalvikvm( 1110): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
I/dalvikvm( 1059): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
I/dalvikvm(  972): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
I/dalvikvm(  868): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
I/dalvikvm( 1012): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
I/Process (  868): Sending signal. PID: 935 SIG: 3                                                                                                                                  
I/dalvikvm(  935): threadid=7: reacting to signal 3                                                                                                                                 
I/dalvikvm(  935): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
I/dalvikvm(  937): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
I/dalvikvm( 1003): Wrote stack trace to '/data/anr/traces.txt'                                                                                                                      
W/WindowManager(  868): No window to dispatch pointer action 1                                                                                                                      
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000                                                                                    
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000                                                                                    
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000                                                                                    
I/ActivityManager(  868): Killing process br.ufs.reconhecimento (pid=1110) at user's request                                                                                        
I/Process (  868): Sending signal. PID: 1110 SIG: 9                                                                                                                                 
I/WindowManager(  868): WIN DEATH: Window{47a85c0 br.ufs.reconhecimento/br.ufs.reconhecimento.GravacaoAtivity paused=false}                                                         
I/WindowManager(  868): WIN DEATH: Window{476ad88 br.ufs.reconhecimento/br.ufs.reconhecimento.Reconhecimento paused=false}                                                          
I/ActivityManager(  868): Process br.ufs.reconhecimento (pid 1110) has died.                                                                                                        
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000                                                                                    
D/dalvikvm(  868): GC freed 11391 objects / 535896 bytes in 562ms                                                                                                                   
I/ActivityManager(  868): Start proc br.ufs.reconhecimento for activity br.ufs.reconhecimento/.Reconhecimento: pid=1124 uid=10017 gids={3003}                                       
I/ActivityManager(  868): Low Memory: No more background processes.                                                                                                                 
D/dalvikvm(  868): GC freed 1110 objects / 44944 bytes in 719ms                                                                                                                     
D/dalvikvm(  935): GC freed 2771 objects / 142472 bytes in 842ms                                                                                                                    
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000                                                                                    
D/dalvikvm( 1037): GC freed 395 objects / 14600 bytes in 1132ms                                                                                                                     
D/dalvikvm( 1012): GC freed 1657 objects / 96120 bytes in 1142ms                                                                                                                    
D/dalvikvm(  972): GC freed 386 objects / 47376 bytes in 1136ms                                                                                                                     
D/dalvikvm( 1044): GC freed 1226 objects / 77848 bytes in 1197ms                                                                                                                    
D/dalvikvm( 1003): GC freed 2193 objects / 157872 bytes in 1230ms                                                                                                                   
D/dalvikvm( 1028): GC freed 1413 objects / 106448 bytes in 1222ms                                                                                                                   
D/dalvikvm(  937): GC freed 454 objects / 21824 bytes in 1233ms                                                                                                                     
D/dalvikvm( 1059): GC freed 3159 objects / 203592 bytes in 1301ms                                                                                                                   
W/InputManagerService(  868): Got RemoteException sending setActive(false) notification to pid 1110 uid 10017                                                                       
W/AudioRecord(  855): obtainBuffer timed out (is the CPU pegged?) user=00000000, server=00000000             

...

!!!AND STAYS ON THIS obtainBuffer timed out FOREVER, EVEN AFTER CLOSING THE APPLICATION!!!

Appreciate if anyone could help me. =)

thiagolee