if (isStop) { return; } if (!isM3u8) { getVideoSize(); } if (!isLocal && !TextUtils.isEmpty(cdn)) { getNodeIp(cdn); } if (!TextUtils.isEmpty(customId)) { if (playUrl.contains("127.0.0.1")) { if (playUrl.contains("version")) { playUrl = playUrl + URLEncoder.encode("&custom_id=" + URLEncoder.encode(customId)); } } else if (playUrl.contains("?")) { playUrl = playUrl + "&custom_id=" + URLEncoder.encode(customId); } else { playUrl = playUrl + "?custom_id=" + URLEncoder.encode(customId); } } try { stop(); reset(); super.setDataSource(context, Uri.parse(playUrl)); } catch (Exception e) { e.printStackTrace(); }
时间: 2024-02-14 13:10:03 浏览: 26
以下是针对该代码的优化建议:
1. 使用早期返回减少嵌套层数
将 `if (isStop)` 的条件判断放在最前面,使用早期返回的方式减少嵌套层数,提高代码可读性。
```
if (isStop) {
return;
}
if (!isM3u8) {
getVideoSize();
}
if (!isLocal && !TextUtils.isEmpty(cdn)) {
getNodeIp(cdn);
}
if (!TextUtils.isEmpty(customId)) {
if (playUrl.contains("127.0.0.1")) {
if (playUrl.contains("version")) {
playUrl = playUrl + URLEncoder.encode("&custom_id=" + URLEncoder.encode(customId));
}
} else if (playUrl.contains("?")) {
playUrl = playUrl + "&custom_id=" + URLEncoder.encode(customId);
} else {
playUrl = playUrl + "?custom_id=" + URLEncoder.encode(customId);
}
}
try {
stop();
reset();
super.setDataSource(context, Uri.parse(playUrl));
} catch (Exception e) {
e.printStackTrace();
}
```
2. 减少重复的判断
在 `if (playUrl.contains("127.0.0.1"))` 的判断中,可以将前面判断 `!TextUtils.isEmpty(customId)` 的条件合并进去,减少重复的判断。
```
if (!TextUtils.isEmpty(customId) && playUrl.contains("127.0.0.1")) {
if (playUrl.contains("version")) {
playUrl = playUrl + URLEncoder.encode("&custom_id=" + URLEncoder.encode(customId));
}
} else if (playUrl.contains("?")) {
playUrl = playUrl + "&custom_id=" + URLEncoder.encode(customId);
} else if (!TextUtils.isEmpty(customId)) {
playUrl = playUrl + "?custom_id=" + URLEncoder.encode(customId);
}
```
3. 简化字符串拼接
在字符串拼接时,可以使用 `String.format()` 方法或者 `StringBuilder` 类来简化代码。
使用 `String.format()`:
```
playUrl = String.format("%s?custom_id=%s", playUrl, URLEncoder.encode(customId));
```
使用 `StringBuilder`:
```
StringBuilder builder = new StringBuilder(playUrl);
if (playUrl.contains("?")) {
builder.append("&");
} else {
builder.append("?");
}
builder.append("custom_id=").append(URLEncoder.encode(customId));
playUrl = builder.toString();
```
综上所述,优化后的代码如下:
```
if (isStop) {
return;
}
if (!isM3u8) {
getVideoSize();
}
if (!isLocal && !TextUtils.isEmpty(cdn)) {
getNodeIp(cdn);
}
if (!TextUtils.isEmpty(customId)) {
if (!playUrl.contains("127.0.0.1")) {
if (playUrl.contains("?")) {
playUrl = playUrl + "&";
} else {
playUrl = playUrl + "?";
}
playUrl = playUrl + "custom_id=" + URLEncoder.encode(customId);
} else if (playUrl.contains("version")) {
playUrl = playUrl + URLEncoder.encode("&custom_id=" + URLEncoder.encode(customId));
}
}
try {
stop();
reset();
super.setDataSource(context, Uri.parse(playUrl));
} catch (Exception e) {
e.printStackTrace();
}
```