应用程序将离开创建辅助线程处理程序的位置

时间:2017-07-10 13:24:38

标签: android multithreading

将应用程序写入Android以了解子线程中对视图项的控制。从名为Mainactivity的主looper中获取并通过构造函数将其传递给实现子线程的类,并且只通过回调更改TextView的内容。

public class MainActivity extends AppCompatActivity {
private TextView textView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.i("create", Thread.currentThread().toString());
    textView = (TextView) findViewById(R.id.textView);
    HandlerTextView handlerTextView = new HandlerTextView(getApplicationContext().getMainLooper());
    handlerTextView.registerMessage(new Message() {
        @Override
        public void handleMessage(String msg) {
            textView.setText(msg);
        }
    });
    HandlerThread handlerThread = new HandlerThread("two", HandlerThread.NORM_PRIORITY);
    if(handlerThread != null){
        Handler a = new Handler(handlerThread.getLooper());
        if(a != null) {
            a.post(handlerTextView);
        }
    }
  }
}

public class HandlerTextView implements Runnable {

private Looper mainLooper = null;
private TextView textView = null;
private Socket socket = null;
private Message message = null;

public HandlerTextView(Looper looper) {
    this.mainLooper = looper;
}

public void registerMessage(Message m) {
    this.message = m;
}

private void setText(final String str) {
    Handler handler = new Handler(mainLooper);
    handler.post(new Runnable() {
        @Override
        public void run() {
            message.handleMessage(str);
        }
    });
}

@Override
public void run() {
    setText("dfsdfsdfsdf");
  }
}
  

创建了一个新的Handlerthread线程处理程序对象,将其作为looper   并将其传递给新处理程序处理程序的构造函数   错误:致命异常:主要                                                                                java.lang.RuntimeException:无法启动活动   ComponentInfo {elaneturn.com.myapplication / elaneturn.com.myapplication.MainActiv引起:java.lang.NullPointerException

1 个答案:

答案 0 :(得分:0)

在创建Handler之前调用handlerThread.start():

handlerThread.start();
Handler a = new Handler(handlerThread.getLooper());