我正试图让一个looper线程工作,但尽管所有的尝试,它崩溃了。我没有使用HandlerThread类,因为我在线程本身做了很多与802.11相关的东西,并且发布了包含大量重复代码的Runnables似乎不是正确的方法。
这里是looper线程类的骨架:
public class WiFiScanner extends Thread {
Looper mLooper;
Handler mHandler;
@Override
public void run() {
Looper.prepare();
synchronized(this) {
mLooper = Looper.myLooper();
notifyAll();
}
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
..... // message parsing
}
}
}
/* waits for Looper initialization */
public boolean waitForLooper() {
synchronized(this) {
while(mLooper == null) {
try {
wait();
} catch (InterruptedException e) {}
}
}
return true;
}
}
以及在主要活动中初始化它的代码:
wifiScanner = new WiFiScanner(
... // callback stuff
);
wifiScanner.start();
wifiScanner.waitForLooper();
wifiScanner.initialize();
initialize是WiFiScanner类中的一个简单函数,它将消息包发布到消息队列:
public void initialize() {
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
WiFiMsg msgId = WiFiMsg.INITIALIZE;
b.putSerializable("msgId", msgId);
msg.obj = b;
mHandler.sendMessage(msg);
}
尽管waitForLooper()成功返回,但对initialize()的调用会导致空指针异常。我假设looper实际上并不处于将消息分派到队列中的状态,因为waitForLooper()和initialize()之间的静态延迟为500ms会绕过这个问题。
有关如何以合理优雅的方式解决这个问题的想法吗?
PS:现在受欢迎的需求,堆栈跟踪:
E/AndroidRuntime( 3178): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime( 3178): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime( 3178): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime( 3178): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
E/AndroidRuntime( 3178): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 3178): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 3178): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime( 3178): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3178): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime( 3178): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime( 3178): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 3178): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3178): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 3178): at de.uni_leipzig.informatik.rvs.videodownload.wifi.WiFiScanner.initialize(WiFiScanner.java:204)
E/AndroidRuntime( 3178): at de.uni_leipzig.informatik.rvs.videodownload.MainActivity.onCreate(MainActivity.java:270)
E/AndroidRuntime( 3178): at android.app.Activity.performCreate(Activity.java:5133)
E/AndroidRuntime( 3178): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime( 3178): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
E/AndroidRuntime( 3178): ... 11 more
答案 0 :(得分:1)
您的通知应该在mHandler设置之后,而不是mLooper - 因为您的NPE在mHandler上。