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

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

@ -16,6 +16,7 @@ import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout; import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.MutableLiveData;
import com.community.pocket.BuildConfig; import com.community.pocket.BuildConfig;
import com.community.pocket.R; import com.community.pocket.R;
@ -65,47 +66,41 @@ public class HttpUtil {
call.enqueue(callback); 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) { public static void checkServer(final Context context, MutableLiveData<Boolean> bool) {
//1.创建OkHttpClient对象 if (Patterns.WEB_URL.matcher(BuildConfig.API_HOST).matches()) {
OkHttpClient okHttpClient = new OkHttpClient(); //1.创建OkHttpClient对象
//2.创建Request对象,设置一个url地址(百度地址),设置请求方式。 OkHttpClient okHttpClient = new OkHttpClient();
Request.Builder builder = new Request.Builder().url(BuildConfig.API_HOST); //2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
//3.创建一个call对象,参数就是Request请求对象 Request.Builder builder = new Request.Builder().url(BuildConfig.API_HOST);
Call call = okHttpClient.newCall(builder.build()); //3.创建一个call对象,参数就是Request请求对象
//4.请求加入调度,重写回调方法 Call call = okHttpClient.newCall(builder.build());
call.enqueue(new Callback() { //4.请求加入调度,重写回调方法
@Override call.enqueue(new Callback() {
public void onFailure(@NotNull Call call, @NotNull IOException e) { @Override
if (BuildConfig.DEBUG) { public void onFailure(@NotNull Call call, @NotNull IOException e) {
Looper.prepare(); bool.postValue(false);
AlertDialog.Builder builder = new AlertDialog.Builder(context); if (BuildConfig.DEBUG) {
View view = View.inflate(context, R.layout.debug_title, null); Looper.prepare();
ImageView imageView = view.findViewById(R.id.close); AlertDialog.Builder builder = getBuilder(context);
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()) {
ConstraintLayout constraintLayout = (ConstraintLayout) View.inflate(context, R.layout.debug, null); ConstraintLayout constraintLayout = (ConstraintLayout) View.inflate(context, R.layout.debug, null);
TextView buildType = constraintLayout.findViewById(R.id.build_type); TextView buildType = constraintLayout.findViewById(R.id.build_type);
buildType.setText(context.getString(R.string.build_type, BuildConfig.BUILD_TYPE)); buildType.setText(context.getString(R.string.build_type, BuildConfig.BUILD_TYPE));
@ -138,35 +133,41 @@ public class HttpUtil {
testPort.setGravity(error.getGravity()); testPort.setGravity(error.getGravity());
linearLayout.addView(testPort, index + 1); linearLayout.addView(testPort, index + 1);
openUrl.setOnClickListener(new View.OnClickListener() { openUrl.setOnClickListener(v -> {
@Override //从其他浏览器打开
public void onClick(View v) { Intent intent = new Intent();
//从其他浏览器打开 intent.setAction(Intent.ACTION_VIEW);
Intent intent = new Intent(); Uri content_url = Uri.parse(BuildConfig.API_HOST);
intent.setAction(Intent.ACTION_VIEW); intent.setData(content_url);
Uri content_url = Uri.parse(BuildConfig.API_HOST); Activity activity = (Activity) context;
intent.setData(content_url); activity.startActivity(Intent.createChooser(intent, context.getString(R.string.choose_browser)));
Activity activity = (Activity) context;
activity.startActivity(Intent.createChooser(intent, context.getString(R.string.choose_browser)));
}
});
});
builder.setView(constraintLayout); builder.setView(constraintLayout);
} else { builder.show();
builder.setMessage(context.getString(R.string.error_api_host, BuildConfig.API_HOST)); 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 { public enum Method {
@ -222,9 +223,7 @@ public class HttpUtil {
if (httpRequest != null) { if (httpRequest != null) {
return httpRequest.value(); return httpRequest.value();
} }
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException | RuntimeException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }

@ -222,4 +222,9 @@
<string name="score_notes">notes:\n%1s</string> <string name="score_notes">notes:\n%1s</string>
<string name="notice_prev">notice prev</string> <string name="notice_prev">notice prev</string>
<string name="notice_next">notice next</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> </resources>

@ -222,4 +222,9 @@
<string name="score_notes">备注信息:\n%1s</string> <string name="score_notes">备注信息:\n%1s</string>
<string name="notice_prev">上一条公告</string> <string name="notice_prev">上一条公告</string>
<string name="notice_next">下一条公告</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> </resources>

@ -223,6 +223,11 @@
<string name="score_notes">notes:\n%1s</string> <string name="score_notes">notes:\n%1s</string>
<string name="notice_prev">notice prev</string> <string name="notice_prev">notice prev</string>
<string name="notice_next">notice next</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 -->
<!-- Strings used for fragments for navigation --> <!-- Strings used for fragments for navigation -->

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