在Android Studio中,我试图将一个字符串写入从WebSockets接收的TextView中。
我在onMessage方法中收到它,然后将其转发到我要编写它的MainActivity。
我的WebSocketListener:
import android.util.Log;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
public class CarWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
private String action;
private String content;
public CarWebSocketListener(String action, String content) {
this.action = action;
this.content = content;
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
if(content.isEmpty()) {
webSocket.send("{\"action\":\"" + action + "\"}");
} else {
webSocket.send("{\"action\":\"" + action + "\", \"content\": " + content + "}");
Log.d("SETMODUS", "{\"action\":\"" + action + "\", \"content\": " + content + "}");
}
webSocket.close(NORMAL_CLOSURE_STATUS, "Closed");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
MainActivity ma = new MainActivity();
ma.setmTextSteer(text);
Log.d("MonitorData", text);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
Log.i("CLOSED", code + " / " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
Log.e("FAILED", t.getMessage());
}
}
这是我尝试编写它的地方(TextView称为mTextSteer):
public void monitorCar(boolean getData) {
if(getData) {
mHandlerMonitoring = new Handler();
mHandlerMonitoring.postDelayed(monitorRunnable, 500);
} else {
if(mHandlerMonitoring != null) {
mHandlerMonitoring.removeCallbacks(monitorRunnable);
mHandlerMonitoring = null;
}
}
}
Runnable monitorRunnable = new Runnable() {
@Override
public void run() {
startWebSocket("getSteeringAngle", "");
//startWebSocket("getSpeed", "");
mHandlerMonitoring.postDelayed(this, 1000);
}
};
public void setmTextSteer(final String text) {
final int steer = Integer.parseInt(text);
Log.d("SetTextOutside", ""+steer);
//mTextSteer.setText(getString(R.string.steer_level, steer));
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("SetTextInside", ""+steer);
mTextSteer.setText(getString(R.string.steer_level, steer));
}
});
}
如果我现在查看我的Logcat,那么我只会一直看到SetTextOutSide:
2019-11-27 10:21:39.379 3625-3821/com.example.autonomesfahren D/SetTextOutside: 90
所以我想我永远也不会进入run()方法。但是对于WebSocket,我需要在runOnUiThread中编写。我还尝试在runOnUiThread之外编写代码,因为您可以看到它的注释位置。如果我取消注释,则会收到以下消息:
2019-11-27 10:21:22.285 3625-3821/com.example.autonomesfahren E/FAILED: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference