android的Looper例子
直接贴代码
MsgThread.java
package bb.aa.looperdemo; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; public class MsgThread extends Thread{ public static final String TAG = "MsgThread"; public Handler _handler = null; @Override public void run() { Log.d(TAG, "进入Thread的run"); Looper.prepare(); // _handler = new Handler(Looper.getMainLooper()){ _handler = new Handler(Looper.myLooper()){ @Override public void handleMessage(Message msg){ Log.d(TAG, "获得了message"); super.handleMessage(msg); } }; Looper.loop(); } public void sendMsg(int what, Object object){ Message message = _handler.obtainMessage(); message.what = what; message.obj = object; _handler.sendMessage(message); } }
MainActiivty.java
package bb.aa.looperdemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private MsgThread _msgThread = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startThread(); Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { _msgThread.sendMsg(123, null); } }); } private void startThread(){ _msgThread = new MsgThread(); _msgThread.start(); } }