【问题标题】:Handler.post() thread, is crashing applicationHandler.post() 线程,正在崩溃应用程序
【发布时间】:2017-11-20 21:41:05
【问题描述】:

我在一个应用程序上工作,它有两个活动。 MainActivity 必须编辑文本才能将 IP 地址和带有 Intent 的端口发送到第二个 Activity2。

我遇到的问题是,当我使用Handler.post() 来更新 UI 线程中的 TextView 时,应用程序崩溃了。没有处理程序线程应用程序正常运行。我认为我的代码是正确的,但我不明白这个问题的原因。

public class Activity2 extends Activity {

private Socket s;
private OutputStream out = null;
private PrintWriter w = null;
private Handler handler = new Handler();
private TextView textView1;
private String tag = "ALEX";
private static String IP;
private static int port;

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

    Bundle extras = getIntent().getExtras(); 
    if (extras != null) {
        IP = extras.getString("IP");
        String port2 = extras.getString("PORT");
        port = Integer.parseInt(port2);
        // Log.v("ip",ip);
        // Log.v("port",port);
    }

Runnable runnable = new Runnable() {
        public void run() {

            synchronized (this) {
                try {
                    s = new Socket(IP, port);
                    out = s.getOutputStream();
                    w = new PrintWriter(out);
                } catch (Exception e) {
                    Log.v("error socket", "Alex soc");
                    e.printStackTrace();
                }
            }

            **handler.post(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        try {
                            Thread.sleep(1000);
                            if (s.isConnected)
                                textView1.setText("connected...");
                            // textView1.setText("not connected...");
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            Log.v("error handler", "handler Alex");
                            e.printStackTrace();
                        }
                    }
                }
            });**

        }
    };
    Thread mythread = new Thread(runnable);
    mythread.start();

【问题讨论】:

  • 你在哪里初始化textView1TextView?

标签: android crash


【解决方案1】:

问题是您在创建活动对象后创建处理程序对象。

应在准备好Looper 之后创建处理程序。

所以你的代码应该是这样的:

private Handler handler;
private TextView textView1;
private String tag = "ALEX";
private static String IP;
private static int port;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity2);
  handler   = new Handler();

【讨论】:

  • 我不明白你在说什么。请详细说明。
猜你喜欢
  • 1970-01-01
  • 2018-09-05
  • 2016-07-01
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多