区分Handler和HandlerThread Handler实例可以在主线程创建,也可以在子线程创建。在子线程中创建时通过Looper,以下示例:
public class MainActivity extends AppCompatActivity { HandlerThread handlerThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handlerThread = new HandlerThread("子线程"); handlerThread.start(); Looper looper = handlerThread.getLooper(); final Handler handler = new Handler(looper) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.d("----->", "线程:" + Thread.currentThread().getName()); } }; findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handler.sendEmptyMessage(100); } }); } @Override protected void onDestroy() { super.onDestroy(); handlerThread.quit(); }}
时间: 2024-10-09 17:35:22