优化检测服务端网络连接异常提示

0515
panqihua 5 years ago
parent 8d82df08d1
commit 6c43376443
  1. 2
      app/build.gradle
  2. 99
      app/src/main/java/com/community/pocket/ui/login/LoginActivity.java
  3. 129
      app/src/main/java/com/community/pocket/util/HttpUtil.java
  4. 5
      app/src/main/res/values-en-rUS/strings.xml
  5. 5
      app/src/main/res/values-zh-rCN/strings.xml
  6. 5
      app/src/main/res/values/strings.xml
  7. 7
      app/src/test/java/com/community/pocket/ExampleUnitTest.java

@ -1,6 +1,6 @@
ext {
//ip地址部分改成ipconfig /all找到的内网地址
API_HOST = 'http://192.168.101.3:8080/'
API_HOST = 'http://192.168.3.132:8080/'
//rap2服务端测试地址ip地址部分改成ipconfig /all找到的内网地址
RAP2_API_HOST = 'http://192.168.101.3:38080/app/mock/1'
}

@ -12,10 +12,9 @@ import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModelProvider;
import com.community.pocket.R;
@ -28,7 +27,6 @@ import com.community.pocket.ui.main.ui.share.Response;
import com.community.pocket.ui.register.RegisterActivity;
import com.community.pocket.ui.resetpwd.ResetPwdActivity;
import com.community.pocket.util.AppDatabase;
import com.community.pocket.util.HttpParse;
import com.community.pocket.util.HttpRequest;
import com.community.pocket.util.HttpResponse;
import com.community.pocket.util.HttpUtil;
@ -41,7 +39,6 @@ import org.xutils.view.annotation.ViewInject;
import java.util.List;
import okhttp3.Call;
import okhttp3.FormBody;
/**
@ -74,17 +71,16 @@ public class LoginActivity extends BaseActivity {
@ViewInject(R.id.login_layout)
private ConstraintLayout layout;
private MutableLiveData<Boolean> bool = new MutableLiveData<>();
/**
* 保存令牌到数据库并跳转到主界面
*/
private void saveTokenToDB(@NotNull final LoginResponse response) {
new Thread(new Runnable() {
@Override
public void run() {
Token token = response.getToken();
sInstance.tokenDao().save(token);
saveToken(response);
}
new Thread(() -> {
Token token = response.getToken();
sInstance.tokenDao().save(token);
saveToken(response);
}).start();
}
@ -107,57 +103,59 @@ public class LoginActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HttpUtil.checkServer(this);
HttpUtil.checkServer(this, bool);
bool.observe(this, aBoolean -> {
if (aBoolean) {
init();
}
});
}
private void init() {
loginViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(LoginViewModel.class);
//后台检查token
hasOnlyUserToken();
//监听token校验状态
loginViewModel.getCheckToken().observe(this, new Observer<LoginResponse>() {
@Override
public void onChanged(LoginResponse loginResponse) {
if (loginResponse.getResult() == com.community.pocket.ui.main.ui.share.Response.Result.OK) {
saveToken(loginResponse);
} else {
layout.setVisibility(View.VISIBLE);
}
loginViewModel.getCheckToken().observe(this, loginResponse -> {
if (loginResponse.getResult() == Response.Result.OK) {
saveToken(loginResponse);
} else {
layout.setVisibility(View.VISIBLE);
}
});
//监听数据校验状态
loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
@Override
public void onChanged(@Nullable LoginFormState loginFormState) {
if (loginFormState == null) {
return;
}
loginButton.setEnabled(loginFormState.isDataValid());
if (loginFormState.getUsernameError() != null) {
usernameEditText.setError(getString(loginFormState.getUsernameError(), PropertiesUtil.getIntValue("username.length")));
}
if (loginFormState.getPasswordError() != null) {
passwordEditText.setError(getString(loginFormState.getPasswordError(), PropertiesUtil.getIntValue("password.length")));
}
loginViewModel.getLoginFormState().observe(this, loginFormState -> {
if (loginFormState == null) {
return;
}
loginButton.setEnabled(loginFormState.isDataValid());
if (loginFormState.getUsernameError() != null) {
usernameEditText.setError(getString(loginFormState.getUsernameError(), PropertiesUtil.getIntValue("username.length")));
}
if (loginFormState.getPasswordError() != null) {
passwordEditText.setError(getString(loginFormState.getPasswordError(), PropertiesUtil.getIntValue("password.length")));
}
});
//监听登陆请求结果
loginViewModel.getLoginResult().observe(this, new Observer<LoginResponse>() {
@Override
public void onChanged(@Nullable LoginResponse loginResponse) {
if (loginResponse == null) {
return;
}
loadingProgressBar.setVisibility(View.GONE);
setResult(Activity.RESULT_OK);
loginViewModel.getLoginResult().observe(this, loginResponse -> {
if (loginResponse == null) {
return;
}
loadingProgressBar.setVisibility(View.GONE);
setResult(Activity.RESULT_OK);
if (loginResponse.getResult() == Response.Result.OK) {
saveTokenToDB(loginResponse);
} else {
loginResponse.toast(getApplicationContext());
}
if (loginResponse.getResult() == Response.Result.OK) {
saveTokenToDB(loginResponse);
} else {
loginResponse.toast(getApplicationContext());
}
});
@ -176,7 +174,6 @@ public class LoginActivity extends BaseActivity {
passwordEditText.addTextChangedListener(afterTextChangedListener);
}
/**
* 查询本地是否有且只有一个用户token如果有则自动登录
*/
@ -191,13 +188,7 @@ public class LoginActivity extends BaseActivity {
List<Token> tokenList = sInstance.tokenDao().queryAll();
if (tokenList != null && tokenList.size() == 1) {
Token currentToken = tokenList.get(0);
HttpUtil.getRequest(HttpUtil.Method.POST, new HttpResponse<>(LoginResponse.class, new HttpParse<LoginResponse>() {
@Override
public void onParseOk(@NotNull Call call, @NotNull okhttp3.Response response, LoginResponse loginResponse) {
loginViewModel.getCheckToken().postValue(loginResponse);
}
}),
HttpUtil.getRequest(HttpUtil.Method.POST, new HttpResponse<>(LoginResponse.class, (call, response, loginResponse) -> loginViewModel.getCheckToken().postValue(loginResponse)),
new FormBody.Builder()
.add("token", currentToken.getToken())
.build()

@ -16,6 +16,7 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.MutableLiveData;
import com.community.pocket.BuildConfig;
import com.community.pocket.R;
@ -65,47 +66,41 @@ public class HttpUtil {
call.enqueue(callback);
}
//关闭弹窗
private static AlertDialog.Builder getBuilder(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
View view = View.inflate(context, R.layout.debug_title, null);
ImageView imageView = view.findViewById(R.id.close);
imageView.setOnClickListener(v -> {
View confirm = View.inflate(context, R.layout.debug_alert, null);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setView(confirm);
final AlertDialog alertDialog = dialog.create();
confirm.findViewById(R.id.yes).setOnClickListener(v1 -> System.exit(0));
confirm.findViewById(R.id.no).setOnClickListener(v12 -> alertDialog.dismiss());
alertDialog.show();
});
builder.setCustomTitle(view);
return builder;
}
//检查服务端连接
public static void checkServer(final Context context) {
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
Request.Builder builder = new Request.Builder().url(BuildConfig.API_HOST);
//3.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(builder.build());
//4.请求加入调度,重写回调方法
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
if (BuildConfig.DEBUG) {
Looper.prepare();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
View view = View.inflate(context, R.layout.debug_title, null);
ImageView imageView = view.findViewById(R.id.close);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View confirm = View.inflate(context, R.layout.debug_alert, null);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setView(confirm);
final AlertDialog alertDialog = dialog.create();
confirm.findViewById(R.id.yes).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.exit(0);
}
});
confirm.findViewById(R.id.no).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
});
builder.setCustomTitle(view);
if (Patterns.WEB_URL.matcher(BuildConfig.API_HOST).matches()) {
public static void checkServer(final Context context, MutableLiveData<Boolean> bool) {
if (Patterns.WEB_URL.matcher(BuildConfig.API_HOST).matches()) {
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
Request.Builder builder = new Request.Builder().url(BuildConfig.API_HOST);
//3.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(builder.build());
//4.请求加入调度,重写回调方法
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
bool.postValue(false);
if (BuildConfig.DEBUG) {
Looper.prepare();
AlertDialog.Builder builder = getBuilder(context);
ConstraintLayout constraintLayout = (ConstraintLayout) View.inflate(context, R.layout.debug, null);
TextView buildType = constraintLayout.findViewById(R.id.build_type);
buildType.setText(context.getString(R.string.build_type, BuildConfig.BUILD_TYPE));
@ -138,35 +133,41 @@ public class HttpUtil {
testPort.setGravity(error.getGravity());
linearLayout.addView(testPort, index + 1);
openUrl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//从其他浏览器打开
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri content_url = Uri.parse(BuildConfig.API_HOST);
intent.setData(content_url);
Activity activity = (Activity) context;
activity.startActivity(Intent.createChooser(intent, context.getString(R.string.choose_browser)));
}
});
openUrl.setOnClickListener(v -> {
//从其他浏览器打开
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri content_url = Uri.parse(BuildConfig.API_HOST);
intent.setData(content_url);
Activity activity = (Activity) context;
activity.startActivity(Intent.createChooser(intent, context.getString(R.string.choose_browser)));
});
builder.setView(constraintLayout);
} else {
builder.setMessage(context.getString(R.string.error_api_host, BuildConfig.API_HOST));
builder.show();
Looper.loop();
}
builder.show();
Looper.loop();
}
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) {
bool.postValue(true);
}
});
} else {
String msg = "\n";
if (BuildConfig.API_HOST.contains(" ")) {
msg += context.getString(R.string.server_address_error_1);
} else if (BuildConfig.API_HOST.contains(":") || BuildConfig.API_HOST.contains("。")) {
msg += context.getString(R.string.server_address_error_2);
} else if (!BuildConfig.API_HOST.startsWith("http")) {
msg += context.getString(R.string.server_address_error_3);
} else {
msg += context.getString(R.string.server_address_error_4);
}
});
getBuilder(context).setMessage(context.getString(R.string.server_address_error, BuildConfig.API_HOST) + msg).show();
}
}
public enum Method {
@ -222,9 +223,7 @@ public class HttpUtil {
if (httpRequest != null) {
return httpRequest.value();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (RuntimeException e) {
} catch (ClassNotFoundException | RuntimeException e) {
e.printStackTrace();
}
}

@ -222,4 +222,9 @@
<string name="score_notes">notes:\n%1s</string>
<string name="notice_prev">notice prev</string>
<string name="notice_next">notice next</string>
<string name="server_address_error">server:%1s error</string>
<string name="server_address_error_1">服务端地址不能包含空格</string>
<string name="server_address_error_2">服务端地址的冒号句号应该是半角符号,\":\"、\".\",而不是全角符号\":\"、\"。\"</string>
<string name="server_address_error_3">服务端地址应该以http开头</string>
<string name="server_address_error_4">恭喜你发现了新的错误,请联系管理员解决问题</string>
</resources>

@ -222,4 +222,9 @@
<string name="score_notes">备注信息:\n%1s</string>
<string name="notice_prev">上一条公告</string>
<string name="notice_next">下一条公告</string>
<string name="server_address_error">服务端地址:%1s不合法</string>
<string name="server_address_error_1">服务端地址不能包含空格</string>
<string name="server_address_error_2">服务端地址的冒号句号应该是半角符号,\":\"、\".\",而不是全角符号\":\"、\"。\"</string>
<string name="server_address_error_3">服务端地址应该以http开头</string>
<string name="server_address_error_4">恭喜你发现了新的错误,请联系管理员解决问题</string>
</resources>

@ -223,6 +223,11 @@
<string name="score_notes">notes:\n%1s</string>
<string name="notice_prev">notice prev</string>
<string name="notice_next">notice next</string>
<string name="server_address_error">server:%1s error</string>
<string name="server_address_error_1">服务端地址不能包含空格</string>
<string name="server_address_error_2">服务端地址的冒号句号应该是半角符号,\":\"、\".\",而不是全角符号\":\"、\"。\"</string>
<string name="server_address_error_3">服务端地址应该以http开头</string>
<string name="server_address_error_4">恭喜你发现了新的错误,请联系管理员解决问题</string>
<!-- Strings used for fragments for navigation -->
<!-- Strings used for fragments for navigation -->

@ -1,5 +1,7 @@
package com.community.pocket;
import android.util.Patterns;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@ -14,4 +16,9 @@ public class ExampleUnitTest {
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
@Test
public void testIP() {
System.out.println(Patterns.WEB_URL.matcher("http:// 192.168.1.1").matches());
}
}
Loading…
Cancel
Save