0

私は問題があります。Android プログラムを実行すると、「残念ながら Android が停止しました」というエラーが表示されます。アプリケーションの実行時にこのエラーが表示されるのはなぜですか? 聞くのは私のファイルです:

enter code here
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;



import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SimpleClientActivityActivity extends Activity {

private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

 //textField = (EditText) findViewById(R.id.editText1); //reference to the text field
  button = (Button) findViewById(R.id.button1);   //reference to the send button

  //Button press event listener
  button.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {

   //messsage = textField.getText().toString(); //get the text message on the text      field
    //textField.setText("");      //Reset the text field to blank

  try {

 client = new Socket("10.0.2.2", 4444);  //connect to server
 printwriter = new PrintWriter(client.getOutputStream(),true);
 printwriter.write(messsage);  //write the message to output stream

 printwriter.flush();
 printwriter.close();
 client.close();   //closing the connection

  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
 });

 }
}

adnroid クライアントを使用して PC サーバーに SMS を送信したい

4

2 に答える 2

4

メインスレッドでネットワーク操作を行っていることが原因である可能性があります。logcat を調べると、赤で情報が表示されます。

于 2012-08-23T18:08:32.183 に答える
1

これを試して

 new Thread(){
        @Override
        public void run(){
            // your onClick code here
        }
    }.start();

また、ネットワーク操作に AsyncTask を使用できます

public class YourTask extends AsyncTask{

    private Context context;
    private ProgressDialog dialog;

    public SplitCueTask(Context context) {
        this.context = context;
        this.dialog = new ProgressDialog(context);           
    }

    @Override
    protected void onPreExecute() {
        dialog.setMessage(getResources().getString(R.string.loading));
        dialog.show();

    }

    @Override
    protected Boolean doInBackground(Object... objects) {
        // you logic here, return result
        return someObject.
    }


    @Override
    protected void onPostExecute(Object someObject) {
        if (dialog.isShowing())
             dialog.dismiss()
        // handle result here, post it on UI or something else
    }


}

タスクを実行

new YourTask(context).execute();    

AndroidManifest に INTERNET PERMISSION を追加することを忘れないでください

<uses-permission android:name="android.permission.INTERNET" />
于 2012-08-23T18:40:31.553 に答える