在以下代码中,我无法接收从我的活动中的线程发送的消息。什么似乎是错的?甚至可以这样做吗?我不想将处理程序对象作为参数传递。
package com.example.mindentropy.testhandler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
private static final String TAG = "MAINACTIVITY";
private ActivityHandler activityHandler;
private TestThread testThread;
static class ActivityHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "In handler");
super.handleMessage(msg);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activityHandler = new ActivityHandler();
testThread = new TestThread();
testThread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
class TestThread extends Thread {
private static final String TAG = "TESTTHREAD";
private final Handler UI_HANDLER = new Handler(Looper.getMainLooper());
public void run() {
while(true) {
Message message = new Message();
Log.d(TAG,"Sending message");
UI_HANDLER.sendMessage(message);
try {
Thread.sleep(1000<<1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}