我試圖讓循環線程工作,但儘管所有嘗試它崩潰。我沒有使用HandlerThread類,因爲我在線程中做了很多與802.11相關的東西,併發布了帶有大量重複代碼的Runnables,這似乎不是正確的方式。Android 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();
初始化是在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()RETURNI ng調用initialize()會導致一個空指針異常。我假設Looper並沒有真正處於將消息分派到隊列中的狀態,因爲waitForLooper()和initialize()之間的靜態延遲爲500ms,從而避免了此問題。
任何想法如何以合理的優雅的方式解決這個問題?
PS:現在大衆的需求,堆棧跟蹤:
E/AndroidRuntime(3178):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211) E/AndroidRuntime(3178) :在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(3) E/AndroidRuntime(3178):at android.app.ActivityThread.main(ActivityThread.java:5103) E/AndroidRuntime(3178):at at android.os.Looper.loop(Looper.java:137) 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(本地方法) E/AndroidRuntime(3178):引起:java.lang.NullPointerException E/AndroidRuntime(3178):at de.uni_leipzig.informatik.rvs.videodownload.wifi .WiFiScanner.initialize(WiFiS canner.java:204) E/AndroidRuntime(3178):at de.uni_leipzig.informatik.rvs.videodownload.MainActivity.onCreate(MainActivity.java:270) E/AndroidRuntime(3178):at android.app.Activity。 E/AndroidRuntime(3178):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) E/AndroidRuntime(3178):at android.app.ActivityThread.performLaunchActivity(ActivityThread。 Java的:2175) E/AndroidRuntime(3178):... 11多個
你可以添加堆棧跟蹤嗎? – user902383
post初始化 – Blackbelt