我目前正在开发一款Android应用程序,可让您在VideoView中观看流媒体视频。我有一种方法允许您通过switch语句选择四个流中的一个。这是正常的,其代码如下:
public void playStream(int position) {
switch (position) {
case 0:
streamOn = true;
streamPos = 0;
logString = "M";
posSelected = "0";
break;
case 1:
streamOn = true;
streamPos = 1;
logString = "J";
posSelected = "1";
break;
case 2:
streamOn = true;
streamPos = 2;
logString = "B";
posSelected = "2";
break;
case 3:
streamOn = true;
streamPos = 3;
logString = "N";
posSelected = "3";
break;
default:
break;
}
checkStreamLink(position);
Log.wtf(logString, posSelected);
Log.wtf(logString, streamURL);
}
无法正常工作的是,在这种选择流的方法中,我调用了另一个运行线程的方法(checkStreamLink();
)。根据您选择的流,线程将调用另一个打开网页的方法,读取一行文本,然后将该文本设置为String streamURL
。这两种方法的代码如下:
public void checkStreamLink(final int position) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
switch (position) {
case 0:
streamURL = getStreamLink("LINK 0 GOES HERE");
break;
case 1:
streamURL = getStreamLink("LINK 1 GOES HERE");
break;
case 2:
streamURL = getStreamLink("LINK 2 GOES HERE");
break;
case 3:
streamURL = getStreamLink("LINK 3 GOES HERE");
break;
default:
break;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
public String getStreamLink (String textSource) {
URL streamURL;
String errorParsingURL = "ERROR PARSING URL";
try {
streamURL = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(streamURL.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
return stringText;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return errorParsingURL;
}
我遇到的问题是String streamURL
在首次使用时返回null,正如我所包含的Log
语句所证明的那样。每次在此之后选择流时,String streamURL
将返回您上次选择流时应收到的文本。我似乎无法弄清楚为什么会发生这种情况,我将不胜感激。
答案 0 :(得分:1)
您将获得null,因为 getStreamLink 在您打印完结果后返回其值。在 getStreamLink 方法的末尾打印结果日志消息,以查看正在返回的实际值,并在该点调用任何其他功能。