我的問題是,在我的MainActivity的onCreate()方法中,我創建了一個新的Thread對象,我想將該對象傳遞給this
活動,並且在該線程中使用它來調用getSystemService ()。但最終,當我啓動應用程序時,它崩潰,我得到NullPointerException。調用getSystemService()時得到NullPointerException異常
我已經發現問題可能是我傳遞引用的活動befor super.onCreate(),但在我的代碼super.onCreate()是在傳遞引用之前執行的。
這是我的MainActivity的onCreate()方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instance which contains thread for obtaining wifi info
final WifiInfoThread wifi_info = new WifiInfoThread(this);
....
}
這是我想獲得參考系統服務
public class WifiInfoThread extends Thread {
// Constructor for passing context to this class to be able to access xml resources
Activity activity;
WifiInfoThread(Activity current) {
activity = current;
}
// Flag for stopping thread
boolean flag = false;
// Obtain service and WifiManager object
WifiManager current_wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
// Runnable object passed to UIThread
Runnable uirunnable = new Runnable() {
@Override
public void run() {
// Get current wifi status
WifiInfo wifi_info = current_wifi.getConnectionInfo();
// Things with showing it on screen
TextView tv_output = (TextView) activity.findViewById(R.id.tv_output);
String info = "SSID: " + wifi_info.getSSID();
info += "\nSpeed: " + wifi_info.getLinkSpeed() + " Mbps";
tv_output.setText(info);
}
};
public void run() {
flag = true;
for(; flag;) {
activity.runOnUiThread(uirunnable);
try {
this.sleep(500);
}
catch(InterruptedException e) {}
}
}
}
親愛的downvoter,用戶剛剛創建了一個帳戶,並提出了一個問題,不要急於下調。也許編輯或評論會受到歡迎。 – iceman